如果要存储多年的成绩怎么办?
为每年创建一个数组? 这种行为和为每一门成绩创建一个变量很像!
多维数组
创建一个二维数组,二维数组是一位数组的自然延伸
double[][] scores = new double[3][6]
double[][] multiDimensionArr = new double[3][5];
for (int i = 0; i < multiDimensionArr.length; i++) {
for (int j = 0; j < multiDimensionArr[i].length; j++) {
System.out.println("multiDimensionArr[" + i + "][" + j + "]=" + multiDimensionArr[i][j]);
}
}
multiDimensionArr[2] = new double[100];
for (int i = 0; i < multiDimensionArr.length; i++) {
System.out.println("multiDimensionArr[" + i + "].length=" + multiDimensionArr[i].length);
}
int YuWenIndex = 0;
int ShuXueIndex = 1;
int WaiYuIndex = 2;
int WuLiIndex = 3;
int HuaXueIndex = 4;
int ShengWuIndex = 5;
String[] names = new String[6];
names[YuWenIndex] = "语文";
names[ShuXueIndex] = "数学";
names[WaiYuIndex] = "外语";
names[WuLiIndex] = "物理";
names[HuaXueIndex] = "化学";
names[ShengWuIndex] = "生物";
Scanner scanner = new Scanner(System.in);
System.out.println("请输入共有多少年的成绩:");
int yearCount = scanner.nextInt();
double[][] scores = new double[yearCount][names.length];
for (int i = 0; i < yearCount; i++) {
for (int j = 0; j < names.length; j++) {
scores[i][j] = 80 + Math.random() * 20;
}
}
System.out.println("请问要查看第几年的成绩?");
int yearToUse = scanner.nextInt() - 1;
System.out.println("请问要查看第几科的成绩?");
int scoreToUse = scanner.nextInt() - 1;
System.out.println("第" + (yearToUse + 1) + "年的第" + (scoreToUse + 1) + "门的成绩是:" + scores[yearToUse][+scoreToUse]);
int YuWenIndex = 0;
int ShuXueIndex = 1;
int WaiYuIndex = 2;
int WuLiIndex = 3;
int HuaXueIndex = 4;
int ShengWuIndex = 5;
String[] names = new String[6];
names[YuWenIndex] = "语文";
names[ShuXueIndex] = "数学";
names[WaiYuIndex] = "外语";
names[WuLiIndex] = "物理";
names[HuaXueIndex] = "化学";
names[ShengWuIndex] = "生物";
double[] year1 = new double[6];
for (int i = 0; i < 6; i++) {
year1[i] = 80 + Math.random() * 20;
}
double[] year2 = new double[6];
for (int i = 0; i < 6; i++) {
year2[i] = 80 + Math.random() * 20;
}
double[] year3 = new double[6];
for (int i = 0; i < 6; i++) {
year3[i] = 80 + Math.random() * 20;
}
double[] yearToUse;
Scanner scanner = new Scanner(System.in);
System.out.println("请输入要查看第几年的成绩:");
int year = scanner.nextInt();
switch (year) {
case 1:
yearToUse = year1;
break;
case 2:
yearToUse = year2;
break;
case 3:
yearToUse = year3;
break;
default:
System.out.println("输入的年份不对,将查看的是最新一年的成绩");
yearToUse = year3;
break;
}
System.out.println("请输入要查看的成绩编号:");
int scoreIndex = scanner.nextInt();
System.out.println("第" + year + "年的" + names[scoreIndex] + "的成绩是:" + yearToUse[scoreIndex]);
|