数组声明创建

发布时间 2023-09-18 13:20:48作者: chengh0618

数组

数组的定义:

数组是相同类型数据的有序集合

每一个数据称作一个数组元素,每个数组元素可以通过一个下标引用它们。

数组声明创建

1、首先必须声明数组变量,才能使用数组,声明数组语法:

dataType[] arrayRefVar; //推荐使用

dataType arrayRefVar[];//效果相同,不推荐

2、Java语言使用new操作符创建数组,语法:

dataType[] arrayRefVar = new dataType[arraySize];

3、数组元素通过索引访问,索引从0开始

4、获取数组长度:arrays.length

public class arrayList {
    public static void main(String[] args) {
        System.out.println(computer(10));
    }

    public static int computer(int n){
        int[] nums = new int[10];
        nums[0] = 1;
        nums[1] = 2;
        nums[2] = 3;
        nums[3] = 4;
        nums[4] = 5;
        nums[5] = 6;
        nums[6] = 7;
        nums[7] = 8;
        nums[8] = 9;
        nums[9] = 10;

        int total = 0;
        for (int i = 0;i < nums.length;i++){
            total = total + nums[i];
        }
        return total;
    }
}