手动输入班级人数,输出班上每个同学的成绩存到数组,,计算出数组中的最大值,最小值,平均值,和总和使用Java
时间: 2024-09-21 13:06:47 浏览: 36
在Java中,你可以按照以下步骤来实现这个功能:
首先,创建一个包含学生成绩的数组,假设我们有一个`StudentScore`类,里面有一个`score`字段表示学生的分数:
```java
public class StudentScore {
private int score;
// 构造函数、getter和setter省略
}
```
然后,创建一个主方法来获取班级人数并输入每个同学的成绩:
```java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入班级人数:");
int totalStudents = scanner.nextInt();
StudentScore[] studentScores = new StudentScore[totalStudents];
for (int i = 0; i < totalStudents; i++) {
System.out.println("请输入第" + (i+1) + "位同学的成绩:");
studentScores[i] = new StudentScore();
studentScores[i].setScore(scanner.nextInt());
}
// 计算最大值、最小值、平均值和总和
int maxScore = findMax(studentScores);
int minScore = findMin(studentScores);
double averageScore = calculateAverage(studentScores);
long sumScore = calculateSum(studentScores);
System.out.println("最大值: " + maxScore);
System.out.println("最小值: " + minScore);
System.out.println("平均值: " + averageScore);
System.out.println("总和: " + sumScore);
}
private static int findMax(StudentScore[] scores) {
return Arrays.stream(scores)
.mapToInt(StudentScore::getScore)
.max()
.orElse(Integer.MIN_VALUE);
}
private static int findMin(StudentScore[] scores) {
return Arrays.stream(scores)
.mapToInt(StudentScore::getScore)
.min()
.orElse(Integer.MAX_VALUE);
}
private static double calculateAverage(StudentScore[] scores) {
int sum = Arrays.stream(scores).mapToInt(StudentScore::getScore).sum();
return (double) sum / scores.length;
}
private static long calculateSum(StudentScore[] scores) {
return Arrays.stream(scores).mapToInt(StudentScore::getScore).sum();
}
}
```
在这个例子中,用户会先输入班级人数,接着依次输入每位同学的成绩。程序会自动计算并输出最大值、最小值、平均值和总和。
阅读全文