目录
1.数组的概述
特点:相同类型数据的一个集合
问题:
发现定义变量太多,不便于数据的处理,于是java定义了数组
概念
1.在java中,数组就是一个变量,用于将相同数据类型的数据存储在内存中,数组中的每一个元素都属于同一数据类型;
2.对变量来说,变量实在内存中分配了一块适合的空间,同样,数组就是在内存中划出了一串连续的空间。
java数组的特点
特点:标识符、数组元素、数组下标、元素类型
数组下标 ![](https://img-blog.csdnimg.cn/3f4c0cbe20b14160a1f2f6df80a94066.png)
注:数组的下标是从0开始,防止越界
什么是java数组
2.数组的使用
声明
数据类型[] 数组名; --》double[] heights;
数据类型 数组名[]; --》String name[];
初始化
1.静态初始化:在初始化时,给出具体的值
2.动态初始化:在初始化时,只给出数组的长度,然后更加需要进行动态赋值。
//接受5名学生的成绩,计算平均分
// int[] score={1,3,5,8,14};//成绩数组
//
// double sum=score[1]+score[2]+score[3]+score[4];
// //计算平均分
// System.out.println(score.length);
// System.out.println("学生平均分是" + sum/score.length);
//动态声明数组
int[] score=new int[2];
score[0]=90;
score[1]=80;
// score[2]=70;数组越界 会抛出异常
System.out.println(score[0]);
System.out.println(score[1]);
常见错误
3. 数据的应用技巧
//定义数组
int[] scores = new int[5];
//输入5名学生的成绩
Scanner input = new Scanner(System.in);//Scanner类是用来输入的
System.out.println("请输入5名学生的成绩");
//输入学生成绩
scores[0]=input.nextInt();//将输入的成绩赋值给数组下标为0的元素
scores[1]=input.nextInt();//将输入的成绩赋值给数组下标为1的元素
scores[2]=input.nextInt();//将输入的成绩赋值给数组下标为2的元素
scores[3]=input.nextInt();//将输入的成绩赋值给数组下标为3的元素
scores[4]=input.nextInt();//将输入的成绩赋值给数组下标为4的元素
//对数组进行升序排序
Arrays.sort(scores);
//将排序后的结果输出
// for (int i = 0 ; i <scores.length;i++){
// System.out.println(scores[i]);
// }
System.out.println(scores[0]);
System.out.println(scores[1]);
System.out.println(scores[2]);
System.out.println(scores[3]);
System.out.println(scores[4]);
//关闭窗口
input.close();
案例: