优化这段代码 public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("请输入本组学员人数"); int people = input.nextInt(); int[] scores = new int[people]; String[] names = new String[people]; for (int i = 0; i <names.length ; i++) { System.out.println("请输入组员姓名和成绩"); names[i] = input.next(); scores[i]= input.nextInt(); } int total = 0; int max = scores[0]; int min = scores[0]; for (int i = 0; i < scores.length; i++) { if(scores[i] > max){ max = scores[i]; } if(scores[i] < min){ min = scores[i]; } total += scores[i]; } int avg = 0; avg = total / people; System.out.println("平均分"+avg); int j = 0; for (int i = 0; i < scores.length-1; i++) { if (scores[i] <= avg){ j++; System.out.println(names[i]+"低于平均分"); } } System.out.println("低于平均分总人数为"+j); System.out.println("最高分"+max); System.out.println("最低分"+min); for (int i = 0; i < names.length; i++) { if (scores[i] == max){ System.out.println("获得最高分的有"+names[i]); } else if (scores[i] == min) { System.out.println("获得最低分的有"+names[i]); } } }
时间: 2023-03-31 22:02:41 浏览: 164
可以将第一个for循环和第二个for循环合并为一个,同时在循环中计算总分和低于平均分的人数,代码如下:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("请输入本组学员人数");
int people = input.nextInt();
int[] scores = new int[people];
String[] names = new String[people];
int total = ;
int max = ;
int min = 100;
int belowAvg = ;
for (int i = ; i < names.length; i++) {
System.out.println("请输入组员姓名和成绩");
names[i] = input.next();
scores[i] = input.nextInt();
total += scores[i];
if (scores[i] > max) {
max = scores[i];
}
if (scores[i] < min) {
min = scores[i];
}
if (scores[i] <= total / people) {
belowAvg++;
System.out.println(names[i] + "低于平均分");
}
}
int avg = total / people;
System.out.println("平均分" + avg);
System.out.println("低于平均分总人数为" + belowAvg);
System.out.println("最高分" + max);
System.out.println("最低分" + min);
for (int i = ; i < names.length; i++) {
if (scores[i] == max) {
System.out.println("获得最高分的有" + names[i]);
} else if (scores[i] == min) {
System.out.println("获得最低分的有" + names[i]);
}
}
}
阅读全文