文章目录
- 1.二维数组定义
- 2.二维数组定义-定义并赋值
- 3.二维数组的遍历
- 4.二维数组案例
- 4.1.案例1
- 4.2.案例2
- 4.3.案例3
1.二维数组定义
- 维数组其实就是数组的数组。
- 二维数组中的每个元素又是一个数组。
- 二维数组的定义:
- 二维数组的声明和赋值:
- 二维数组的注意事项:
- 创建二维数组的时候,一定要定义第一维的长度。
2.二维数组定义-定义并赋值
- 写法一
- 写法二
存储的结构:
3.二维数组的遍历
/*
* 循环遍历二维数组
*/
public class Demo3 {
public static void main(String[] args) {
int[][] scores = new int[][] { { 90, 85, 92, 78, 54 }, { 76, 63, 80 },{ 87, 70 } };
for (int i = 0; i < scores.length; i++) {
for (int j = 0; j < scores[i].length; j++) {
System.out.print(scores[i][j] + "\t");
}
System.out.println("");
}
}
}
4.二维数组案例
4.1.案例1
一起来参加屌丝程序员大赛吧,有3个班各3名程序员参赛,记录每个学员的成绩,并计算每个班的平均分
/**
二位数组示例:JAVA中没有真正的多维数组,多维数组的表示方式是数组中的元素还是数组
*/
public class a
{
public static void main(String[] args)
{
int[][] scores = {{78,92,84},{86,99,80},{69,75,86}};
int classLen = scores.length;
for(int i = 0;i < classLen;i++)
{
int sum = 0;
int count = scores[i].length;
for(int j = 0;j < count;j++)
{
sum += scores[i][j];
}
int avg = sum / count;
//这里(i+1)一定要括起来,不然会多显示数字
System.out.println("第"+(i+1)+"班同学的平均成绩是:"+avg);
}
}
}
4.2.案例2
/*
* 使用二维数组存储数据
*/
public class Demo4 {
public static void main(String[] args) {
int[][] scores=new int[3][5]; //定义一个二维数组
Scanner input=new Scanner(System.in);
//动态从键盘上输入所有数组的值
for (int i = 0; i < scores.length; i++) {
System.out.println("***********第"+(i+1)+"个班*************");
for (int j = 0; j < scores[i].length; j++) {
System.out.print("请输入第"+(j+1)+"个学生成绩:");
int num=input.nextInt();
scores[i][j]=num; //动态从键盘输入值 按顺序存入数组
}
}
//计算每个班的总成绩
for (int i = 0; i < scores.length; i++) {
int sum=0; //求和 每个班的成绩
for (int j = 0; j < scores[i].length; j++) {
sum=sum+scores[i][j];
}
System.out.println((i+1)+"班的总成绩是:"+sum);
}
}
}
4.3.案例3
求二维数组中元素最大值与最小值
public class TwoDArrayMinMax {
public static void main(String[] args) {
int[][] array = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
if (array[i][j] < min) {
min = array[i][j];
}
if (array[i][j] > max) {
max = array[i][j];
}
}
}
System.out.println("Minimum value: " + min);
System.out.println("Maximum value: " + max);
}
}