编写java程序,输入10个成绩,计算最高分、最低分、平均分,并按从小到大排序,统计高于平均分的人数。
1个回答
展开全部
Java 8 以上(包含java8) Lambda 方式,这种方式比较简洁,代码如下:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class App20 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
List<Float> scores = new ArrayList<>();
System.out.println("请输入10个人的成绩:");
for (int i = 0; i < 10; i++) {
scores.add(scanner.nextFloat());
}
float max = scores.stream().max((x, y) -> Float.compare(x, y)).get();
System.out.println("最高分:" + max);
float min = scores.stream().min((x, y) -> Float.compare(x, y)).get();
System.out.println("最低分:" + min);
float average = scores.stream().reduce(0.0f, Float::sum) / scores.size();
System.out.println("平均分:" + average);
scores.sort((x, y) -> Float.compare(x, y));
System.out.println("从小到大分数排序:");
scores.forEach(s -> System.out.print(s + " "));
long n = scores.stream().filter(r -> r > average).count();
System.out.println("\n高于平均分的有" + n + "个");
}
}
传统方式,如下:
import java.util.Arrays;
public class App21 {
public static void main(String[] args) {
float[] scores = new float[] { 10f, 9f, 8f, 7f, 6f, 5f, 4f, 3f, 2f, 1f };
float max = Float.MIN_VALUE;
for(float score : scores) {
if (score > max) {
max = score;
}
}
System.out.println("最高分:" + max);
float min = Float.MAX_VALUE;
for(float score : scores) {
if (score < min) {
min = score;
}
}
System.out.println("最低分:" + min);
float sum = 0;
for(float score : scores) {
sum += score;
}
float average = sum / scores.length;
System.out.println("平均分:" + average);
// 从小到大排序
Arrays.sort(scores);
System.out.println("从小到大分数排序:");
for(float score : scores) {
System.out.print(score + " ");
}
int n = 0;
for(float score : scores) {
if (score > average)
n++;
}
System.out.println("\n高于平均分的有" + n + "个");
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询