数组的使用步骤
(1) 声明数组:告诉计算机数据类型是什么
int[ ] score1; //Java成绩
int score2[ ]; //C#成绩
String[ ] name; //学生姓名
语法:
数据类型 数组名[ ] ;
数据类型[ ] 数组名 ;
(2) 分配空间:告诉计算机分配几个连续的空间
score = new int[30];
avgAge = new int[6];
name = new String[30];
语法:
数据类型[ ] 数组名=new 数据类型[大小];
(3) 赋值:向分配的空间里放数据
score[0] = 89;
score[1] = 79;
score[2] = 76;
……
此外也可以边声明边赋值:
int[ ] score = {89, 79, 76};
或
int[ ] score = new int[ ]{89, 79, 76};
(4) 处理数组
取数组中的元素,求平均分:
int [ ] score = {60, 80, 90, 70, 85};
double avg;
avg = (score[0] + score[1] + score[2] + score[3] + score[4])/5;
结合循环:
数组的元素类型和数组的大小都是确定的,所以当处理数组元素时候,我们通常使用基本循环或者 For-Each 循环。
public class TestArray {
public static void main(String[] args) {
double[] myList = {1.9, 2.9, 3.4, 3.5};
// 打印所有数组元素
for (int i = 0; i < myList.length; i++) {
System.out.println(myList[i] + " ");
}
// 计算所有元素的总和
double total = 0;
for (int i = 0; i < myList.length; i++) {
total += myList[i];
}
System.out.println("Total is " + total);
// 查找最大元素
double max = myList[0];
for (int i = 1; i < myList.length; i++) {
if (myList[i] > max) max = myList[i];
}
System.out.println("Max is " + max);
}
}
以上实例编译运行结果如下:
1.9
2.9
3.4
3.5
Total is 11.7
Max is 3.5