Day22-Array数组

版权声明:啥是版权,感觉都是侵权必究。我也会究的。 https://blog.csdn.net/Scan_13286/article/details/84642025

Day22-Array数组。

数组…Emmmm,要怎么描述,算了不描述了
今天才将的for循环,昨天就写完了。然后补了点,我可真是个小机灵鬼呀~


1.数组的声明方式

		//第一种数组的声明
		int[] stuScore = new int[30];
		//第二种数组的声明
		int[] stuScore2 = new int[]{1,2,3,4,5};
		//第三种数组的声明
		int[] stuScore3 = {1,2,3,4,5};

中括号放在变量名前,变量名后都是可以的。

		//第一种数组的声明
		int []stuScore = new int[30];
		//第二种数组的声明
		int stuScore2[] = new int[]{1,2,3,4,5};
		//第三种数组的声明
		int[] stuScore3 = {1,2,3,4,5};

2.获取数组长度

		System.out.println(stuScore.length);
		System.out.println(stuScore2.length);
		System.out.println(stuScore3.length);

通过数组名.length的方法获取。


3.给单个数组元素赋值

		String[] foods = new String[4];
		foods[0] = "milk";
		foods[1] = "egg";
		foods[2] = "peken";
		foods[3] = "cookies";

如果继续写foods[4] = "coffee";,则会报错,因为声明数组的时候,已经声明数组长度为4,如果添加第五个,则会报数组溢出的错误。


4.遍历数组

遍历数组需要结合for循环。

		int[] stuScore = new int[30];
		for(int i = 0;i < stuScore.length;i++){
			stuScore[i] = i;
		}

循环遍历每一个数组元素,并给每个元素赋值 i 。


更完,有点少的说。吧啦吧啦噗噗噗噗噗~

猜你喜欢

转载自blog.csdn.net/Scan_13286/article/details/84642025