?
?
数组的基本结构:
注意:
?
如何使用数组 分为四步:
1.声明数组:
2.语法:
3.分配空间:告诉计算机分配几个连续的空间
4.赋值:向分配的格子里放数据
score[0] = 89; score[1] = 79; score[2] = 76; …比较麻烦
Scanner input = new Scanner(System.in);
for(int i = 0;i<30;i++){
score[i] = input.nextInt();
}
?
5.处理数据
对数据进处理:计算5位学生的平均分
int [] scores = {60, 80, 90, 70, 85};
double avg;
avg = (scores[0] + scores[1] + scores[2] + scores[3] + scores[4])/5;
int [] scores = {60, 80, 90, 70, 85};
int sum = 0;
double avg;
for(int i = 0; i < scores.length; i++){
sum = sum + scores[i];
}
avg = sum / scores.length;
增强for循环:
public static void main(String[] args) {
int[] nums ={11,25,63,48,19,33,26,87,93,45,11,20,66,55,99,17,10,33,59,68,80,40};
//使用增强for循环遍历数组
for(int a :nums){
System.out.print(a+" ");
}
}
}
数组的动态初始化和静态初始化的区别:
常见错误1:
public class ErrorDemo1 {
public static void main(String[ ] args){
int[ ] score = new int[ ];//编译出错,没有写明数组的大小
score[0] = 89;
score[1] = 63;
System.out.println(score[0]);
}
}
常见错误2:
int[ ] scores = new int[2];
scores[0] = 90;
scores[1] = 85;
scores[2] = 65;//数组越界,数组长度为2,这里是第三个
System.out.println(scores[2]);
常见错误3:
int[ ] score = new int[5];
score = {60, 80, 90, 70, 85};
int[ ] score2;
score2 = {60, 80, 90, 70, 85};
//编译出错,创建数组并赋值的方式必须在一条语句中完成