数组用于存储多个相同类型数据的组合。
一、一维数组
1、定义数组
数组有四个基本要素:

(1)标识符:数组名称,和变量名的意义相同命名规则相同
(2)数组元素:存储的数据
(3)元素下标:从0开始,即给存储的数据编号,方便我们赋值与调用
(4)元素类型:定义数组存储数据类型
(5)数组长度:即存储的数据数量,如数组长度为5,只能存储5个数据
如何定义数组呢:

定义并给数组赋值一般有三种使用方法
(1)
int scores[];//声明数组,int为数组类型,scores为数组名,[]为数组长度,但是定义是不能定义数组长度
scores=new int[5];//定义数组长度,数组长度为5
scores[0]=100;//[]内为元素下标,从0开始
scores[1]=100;
scores[2]=100;
scores[3]=100;
scores[4]=100;
(2)
int[] scores = new int[5];//这里就是在定义数组时,同时定义数组长度,数组长度为5
scores[0]=100;//[]内为元素下标,从0开始
scores[1]=100;
scores[2]=100;
scores[3]=100;
scores[4]=100;
(3)
int scores[]=new int[]{100,100,100,100,100};
int scores[]={100,100,100,100,100};//方式三第二种赋值方法,定义数组时直接赋值,赋值的数据数量及为数组长度
2、遍历数组
调用数组中存储的数据,通常与循环一起使用
public class Test2 {
public static void main(String[] args) {
int scores[];
scores=new int[10];
scores[0]=100;
scores[1]=100;
scores[2]=100;
scores[3]=100;
scores[4]=100;
scores[5]=100;
scores[6]=100;
scores[7]=100;
scores[8]=100;
scores[9]=100;
for(int i=0;i<10;i++){
System.out.println("第"+(i+1)+"名学生的成绩为:"+scores[i]);
//在for循环里将存储的数据输出,因为数组下标从0开始。
//所以定义i初始值为0,当i=0时,输出第一名学生成绩存储在scores[0]中
}
}
}
二、二维数组
1、二维数组语法格式:
数据类型[ ][ ] 数组名
或者
数据类型 数组名[ ][ ]
二维数组的定义与操作与一维数组数组相似,从内存角度讲二维数组时用一维数组存储起来的一维数组,实际上是一个一维数组,每个元素它又是一个一维数组。
例如int[ ][ ] S=new int[3][5],数组名为S,有三个元素,分别是S[0],S[1],S[2],每个元素又是一个一维数组,S[0]就是数组名称,包括五个元素分别为S[0][1],S[0][2],S[0][3],S[0][4],具体如下如所示:

2、二维数组的使用
直接赋值:
int[][] num=new int[][]{{5,6,9,7,1},{9,2,7,9},{1}};
//或者
int[][] num={{5,6,9,7,1},{9,2,7,9},{1}};
遍历:
import java.util.Scanner;
public class Test2 {
public static void main(String[] args) {
int[][] scores = new int[3][5];
int sum = 0;
double avg = 0;
int count = 0;
Scanner input = new Scanner(System.in);
for (int i = 0; i < scores.length; i++) {
System.out.println("请输入第" + (i + 1) + "个班级成绩:");
count += scores[i].length;
for (int j = 0; j < scores[i].length; j++) {
System.out.print("请输入第" + (j + 1) + "为位同学成绩:");
scores[i][j] = input.nextInt();
sum += scores[i][j];
}
}
avg = sum / count;
System.out.println("三个班级总成绩为:" + sum);
System.out.println("三个班级平均分为:" + avg);
}
}
三、Arrays类使用
Arrsys是java.utile包提供的工具类,所以在使用的时候要先导入。Arraysl类提供了许多数组的方法常用的有一下几种:

示例:将数组排序并且查询下标
import java.util.Arrays;//一定要先导入Arrays类
public class Test1 {
public static void main(String[] args) {
char[] temp = { 'b', 'd', 'a', 'c' };
Arrays.sort(temp);//将数组按照升序方法排序,字符按照ASCII码排序
for (char temps : temp) {// 增强for循环,不能改变数组的元素
System.out.println(temps);
}
int result = Arrays.binarySearch(temp, 'a');//查询元素在数组中的下标,前提是数组一定要按照升序排列
System.out.println(result);
}
}
494

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



