Java循环3个班级,再循环录入该班级的5个学生的序号和成绩,录入学号时判断长度,录入分值时判断是否为负数,录入完一个班级后打印出该班级平均分和及格人数,当全部录入完毕后计算平均分和及格人数并显示
时间: 2024-09-30 16:10:51 浏览: 27
在Java中,我们可以创建一个更复杂的数据结构,比如二维数组或列表来处理这种需求。以下是一个示例,使用嵌套循环来实现:
```java
import java.util.ArrayList;
import java.util.Scanner;
class Student {
String id;
double score;
Student(String id, double score) {
this.id = id;
if (id.length() > 0) {
this.score = score;
} else {
throw new IllegalArgumentException("学号不能为空");
}
if (score < 0) {
throw new IllegalArgumentException("成绩不能为负数");
}
}
}
public class ClassGrade {
private ArrayList<ArrayList<Student>> classes;
private double overallAverage = 0;
private int totalPasses = 0;
public ClassGrade(int numClasses, int studentsPerClass) {
classes = new ArrayList<>();
for (int i = 1; i <= numClasses; i++) {
ArrayList<Student> classStudents = new ArrayList<>();
for (int j = 1; j <= studentsPerClass; j++) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入第 " + i + " 班第 " + j + " 学生的学号:");
String id = scanner.next();
if (id.isEmpty()) {
throw new IllegalArgumentException("学号不能为空");
}
System.out.println("请输入第 " + i + " 班第 " + j + " 学生的成绩:");
double score = scanner.nextDouble();
if (score < 0) {
throw new IllegalArgumentException("成绩不能为负数");
}
classStudents.add(new Student(id, score));
scanner.close();
}
classes.add(classStudents);
printClassInfo(i, classStudents);
}
calculateOverallAverage();
}
private void printClassInfo(int className, ArrayList<Student> classStudents) {
double classAverage = calculateClassAverage(classStudents);
int passes = countPasses(classStudents);
System.out.println("班级 " + className + " 平均分: " + classAverage);
System.out.println("班级 " + className + " 及格人数: " + passes);
overallAverage += classAverage;
totalPasses += passes;
}
private double calculateClassAverage(ArrayList<Student> classStudents) {
double sum = 0;
for (Student student : classStudents) {
sum += student.score;
}
return sum / classStudents.size();
}
private int countPasses(ArrayList<Student> classStudents) {
int passes = 0;
for (Student student : classStudents) {
if (student.score >= 60) {
passes++;
}
}
return passes;
}
public void calculateOverallAverage() {
if (totalStudents() > 0) {
overallAverage /= totalStudents();
}
System.out.println("所有班级的平均分: " + overallAverage);
System.out.println("总及格人数: " + totalPasses);
}
private int totalStudents() {
int total = 0;
for (ArrayList<Student> classStudents : classes) {
total += classStudents.size();
}
return total;
}
public static void main(String[] args) {
int numClasses = 3;
int studentsPerClass = 5;
ClassGrade grade = new ClassGrade(numClasses, studentsPerClass);
}
}
```
这个代码会按班录入学生的学号和成绩,每次录入完成后会打印出班级信息,包括平均分和及格人数。录入完毕后,会计算整体的平均分和总及格人数。
阅读全文