有 5 个学生,每个学生的数据包括学号、班级、姓名、三门课成绩。从键盘输入5 个学生数据,要求打印出每个学生三门课的平均成绩,以及平均分最高分学生的所有数据。
10条回答 默认 最新
- 晨曦之光Wing 2020-12-12 18:51关注
import java.util.Scanner; public class CalculateScore { public static void main(String[] args) { System.out.println("请依次输入5个学生的数据:学号、班级、姓名、三门课成绩(以空格隔开)"); Scanner scanner = new Scanner(System.in); // 5行7列,最后一列用来存平均成绩 Object[][] array = new Object[5][7]; int enterCount = 0; while (enterCount < 5) { String line = scanner.nextLine(); String[] strings = line.split(" "); array[enterCount][0] = strings[0]; array[enterCount][1] = strings[1]; array[enterCount][2] = strings[2]; double score1 = Double.parseDouble(strings[3]); array[enterCount][3] = score1; double score2 = Double.parseDouble(strings[4]); array[enterCount][4] = score2; double score3 = Double.parseDouble(strings[5]); array[enterCount][5] = score3; double avgScore = (score1 + score2 + score3) / 3; array[enterCount][6] = avgScore; enterCount++; } double maxAvgScore = (double) array[0][6]; int maxAvgScoreStuIndex = 0; for (int index = 0; index < array.length; index++) { double score = (double) array[index][6]; if (score > maxAvgScore) { maxAvgScore = score; maxAvgScoreStuIndex = index; } } String format = "%.2f"; // 保留两位小数 System.out.println("所有学生的平均成绩如下:"); for (int index = 0; index < array.length; index++) { System.out.println( array[index][2] + ": " + String.format(format, (double) array[index][6])); } System.out.println("平均分最高分学生数据如下:"); StringBuilder str = new StringBuilder(); for (int index = 0; index < array[maxAvgScoreStuIndex].length; index++) { if (index == array[maxAvgScoreStuIndex].length - 1) { str.append(String.format(format, (double) array[maxAvgScoreStuIndex][index])); } else { str.append(array[maxAvgScoreStuIndex][index]); } str.append(" "); } System.out.println(str.toString()); } }
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 9无用