一:二维数组
1:定义
二维数组的长度是数组的元素个数,每个元素就是一个一维数组,而且这个一维数组的元素个数可以不一样。
二维数组是由多个一维数组组成的数据结构,它可以理解为一个表格或者矩阵。每个一维数组称为行,而每个元素则是列。二维数组可以用来存储和处理具有多个维度的数据。
在编程中,二维数组的定义通常是通过指定行数和列数来创建。
例如,一个3行4列的二维数组可以这样定义:
int[][] array = new int[3][4];
这样就创建了一个3行4列的整型二维数组。你可以根据需要访问和操作数组中的元素,例如通过下标访问特定的元素:
array[0][0] = 1; // 设置第一行第一列的元素为1
2:二维数组初始化
int[][] scores = new int{
{11,12,43},
{23,45,35},
{32,45,12}
};
3:二维数组的遍历
public class Pratice4 {
public static void main(String[] args) {
int[][] scores = {
{78, 89, 93}, // 260
{88, 92, 89}, // 269
{79, 87, 88}, // 254
{92, 96, 99}, // 287
{94, 90, 87} // 271
};
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:二维数组的排序
(1)设计程序按照各个学生的 Java 成绩进行排序 ( 降序 )
public class Pratice5 {
public static void main(String[] args) {
String[] names = {"安琪拉", "王昭君", "蔡文姬", "妲己", "张良"};
// 设 courses 数组中依次存放三门课程的名称
String[] courses = {"C++", "Java", "Python"};
// 设 scores 数组中依次存储的是 names 数组中各个学生的 C++ 、Java 、Python 课程的成绩
int[][] scores = {
{90, 89, 75},
{59, 40, 100},
{100, 99, 80},
{80, 61, 61},
{60, 100, 99},
};
for (int i = 0; i < scores.length - 1; i++) { // 控制排序的次数
for (int j = 0; j < scores.length - i - 1; j++) {// 两两比较的次数
if (scores[j][1] < scores[j + 1][1]) {
// 成绩交换
int[] temp = scores[j];
scores[j] = scores[j + 1];
scores[j + 1] = temp;
// 名字交换
String t = names[j];
names[j] = names[j + 1];
names[j + 1] = t;
}
}
}
//遍历输出
for (int i = 0; i < names.length; i++) {
System.out.print(names[i] + ": ");
for (int j = 0; j < scores[i].length; j++) {
System.out.print(courses[j] + "=" + scores[i][j] + "\t");
}
System.out.println();
}
}
}
(2)设计程序,根据学生总成绩进行排序(降序排列),并输出学生姓名、每门课程的名称和
* 该学生的成绩、该学生的总成绩
public class Exer03 {
public static void main(String[] args) {
// 设 names 数组中存放学生姓名
String[] names = {"安琪拉", "王昭君", "蔡文姬", "妲己", "张良"};
// 设 courses 数组中依次存放三门课程的名称
String[] courses = {"C++", "Java", "Python"};
// 设 scores 数组中依次存储的是 names 数组中各个学生的 C++ 、Java 、Python 课程的成绩
int[][] scores = {
{90, 89, 75},
{59, 40, 100},
{100, 99, 80},
{80, 61, 61},
{60, 100, 99},
};
int[] sumArr = new int[scores.length];
for (int i = 0; i < scores.length; i++) {
int sum = 0;
for (int j = 0; j < scores[i].length; j++) {
sum += scores[i][j];
}
sumArr[i] = sum;
}
// 选择排序(降序)
for (int i = 0; i < scores.length - 1; i++) {
int max = i;
for (int j = i + 1; j < scores.length; j++) {
if (sumArr[j] > sumArr[max]){
max = j;
}
}
int temp = sumArr[i];
sumArr[i] = sumArr[max];
sumArr[max] = temp;
String n = names[i];
names[i] = names[max];
names[max] = n;
int[] s = scores[i];
scores[i] = scores[max];
scores[max] = s;
}
// 输出每个人的各科成绩 安琪拉: c++=90 java=89 python=75
for (int i = 0; i < names.length; i++) {
System.out.print(names[i] + ": ");
for (int j = 0; j < scores[i].length; j++) {
System.out.print(courses[j] + "=" + scores[i][j] + "\t");
}
System.out.println(sumArr[i]);
System.out.println();
}
}
}