第六章 一维数组及经典应用
1.数组
数组是一个变量,存储相同数据类型的一组数据
声明一个变量就是在内存空间划出一块合适的空间
声明一个数组就是在内存空间划出一串连续的空间
数组基本要素
标识符
数组元素
元素下标:从0开始
元素类型
数组中的所有元素必须属于相同的数据类型
使用数组四步走
1.声明数组 int[ ] a; 告诉计算机数据类型是什么
2.分配空间 a = new int[5]; 告诉计算机分配几个连续的空间
3.赋值 a [0] = 8; 向分配的格子里放数据
4.处理数据 a [0] = a[0] * 10
声明数组并分配空间
数据类型[ ] 数组名 = new 数据类型[大小] ;
数组赋值
方法1: 边声明边赋值
int[ ] scores = {89, 79, 76};
int[ ] scores = new int[ ]{89, 79, 76};
方法2:动态地从键盘录入信息并赋值
Scanner input = new Scanner(System.in);
for(int i = 0; i < 30; i ++){
scores[i] = input.nextInt();
}
处理数据
对数据进行处理:计算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;
数组与内存

常见错误
public class ErrorDemo1 {
public static void main(String[ ] args){
int[ ] score = new int[ ]; 编译出错,没有写明数组的大小
score[0] = 89;
score[1] = 63;
System.out.println(score[0]);
}
}
int[ ] scores = new int[2];
scores[0] = 90;
scores[1] = 85;
scores[2] = 65; 编译出错,数组越界
System.out.println(scores[2]);
int[ ] score = new int[5];
score = {60, 80, 90, 70, 85};
int[ ] score2;
score2 = {60, 80, 90, 70, 85};
编译出错,创建数组并赋值的方式必须在一条语句中完成
, 70, 85};
int[ ] score2;
score2 = {60, 80, 90, 70, 85};
编译出错,创建数组并赋值的方式必须在一条语句中完成


被折叠的 条评论
为什么被折叠?



