在Java中,使用For循环实现:假设一个班有两个个学生,各有三门课,输入学生姓名,各门课的成绩,求各个学生的总分,平均分,最高分,最低分,以及整个班级的总分,平均分,最高分,最低分。
时间: 2024-10-27 14:11:43 浏览: 29
在Java中,你可以通过for循环遍历每个学生和他们的成绩,然后分别计算个人和班级的统计数据。这里是一个简单的示例代码:
```java
import java.util.Scanner;
class Student {
String name;
double[] scores = new double[3]; // 假设每门课满分100
// 构造函数、getter和setter省略
}
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int studentsCount = 2; // 班级人数
Student[] students = new Student[studentsCount];
for (int i = 0; i < studentsCount; i++) {
System.out.println("请输入第" + (i+1) + "位学生的名字:");
students[i] = new Student();
students[i].setName(scanner.nextLine());
// 输入每门课程成绩
for (int j = 0; j < 3; j++) {
System.out.println("请输入第" + (j+1) + "门课程的成绩:");
students[i].scores[j] = scanner.nextDouble();
}
}
// 计算个人和班级统计
double totalScore, averageScore, highestScore, lowestScore;
for (Student student : students) {
totalScore = calculateTotal(student.scores);
averageScore = totalScore / 3;
highestScore = Collections.max(Arrays.asList(student.scores));
lowestScore = Collections.min(Arrays.asList(student.scores));
// 输出个人统计结果
System.out.println("学生:" + student.name);
System.out.println("总分: " + totalScore);
System.out.println("平均分: " + averageScore);
System.out.println("最高分: " + highestScore);
System.out.println("最低分: " + lowestScore);
System.out.println("-------------------------");
}
// 班级总分、平均分、最高分和最低分
double classTotal = Arrays.stream(students).mapToDouble(Student::getTotalScore).sum();
double classAverage = classTotal / studentsCount;
double classHighest = Arrays.stream(students).mapToInt(Student::getHighestScore).max().orElse(0);
double classLowest = Arrays.stream(students).mapToInt(Student::getLowestScore).min().orElse(0);
System.out.println("班级总分: " + classTotal);
System.out.println("班级平均分: " + classAverage);
System.out.println("班级最高分: " + classHighest);
System.out.println("班级最低分: " + classLowest);
scanner.close();
}
private static double calculateTotal(double[] scores) {
return Arrays.stream(scores).sum();
}
}
```
这个程序首先创建了两个学生对象,然后依次获取他们的名字和课程成绩。接着,它会计算每位学生的个人成绩信息,并在结束后计算全班的总体统计算法。
阅读全文