Java array -09 days study notes

Array

The array variable must be declared before the array can be used in the program. The following is the syntax for declaring array variables:

dataType[] arrayRefVar;
//变量的类型 变量的名字 = 变量的值;
//数组类型 数组的名字 ;
int[] nums1 ;  //定义数组

Preferred method
or

dataType arrayRefVar[]; 
int nums2[];

Same effect, but not the preferred method

The Java language uses the new operator to create an array, the syntax is as follows:

dataType[] arrayRefVar = new dataType[arraySize];

 nums1 = new int[10];  //这里可以存放10个int类型的数字
  • The elements of the array are accessed by index, and the array index starts from 0.
  • Get the length of the array:

arrays . length

You can define and create an array in one sentence later

int[] nums = new int[10];
public static void main (String[] args){
								
	//数组类型
	int[] nums1;  //1.声明一个数组
								
	nums1 = new int[10];   //2.创建一个数组  
	// int[10]代表可以存放0-9这10个int类型的数字
	// 所有类型都是int类型的不会有String类型
	// 没有赋值的数组 默认是0或者null
								
	// 3.给数组赋值
								
	//也可以合成一句话
	//int[] nums = new int[10];
	nums1[0]= 1;
	nums1[1]= 2;
	nums1[2]= 3;
	nums1[3]= 4;
	nums1[4]= 5;
	nums1[5]= 6;
	nums1[6]= 7;
	nums1[7]= 8;
	nums1[8]= 9;
	nums1[9]= 10;
	System.out.println(nums1[9]);//输出数组中的9
								
	int sum = 0;
	for(int i = 0;i<nums1.length;i++){
												
	sum= sum+nums1[i];
	System.out.println("第"+i+"个数字的和:"+sum);
	}
	System.out.println("总和"+sum);
								
	}

Guess you like

Origin blog.csdn.net/yibai_/article/details/114603720