用java代码完成上述代码
时间: 2024-10-02 17:01:18 浏览: 28
当然可以,以下是使用Java完成上述代码的例子:
```java
import java.util.Scanner;
public class ScoreManagement {
public static void main(String[] args) {
String[][] classScores = new String[3][5]; // 创建3个班级,每班5个学生
Scanner scanner = new Scanner(System.in);
for (int i = 0; i < 3; i++) { // 3个班级
for (int j = 0; j < 5; j++) { // 每班5人
System.out.print("请输入第" + (i+1) + "班第" + (j+1) + "位同学的学号(三位数):");
String studentId = scanner.nextLine();
if (!isValidStudentId(studentId)) {
System.out.println("学号输入错误,请输入三位数字的学号。");
continue;
}
System.out.print("请输入分数:");
int score = scanner.nextInt();
if (score < 0) {
System.out.println("分数输入错误,不允许负分,请重新输入。");
continue;
}
classScores[i][j] = studentId + "," + score;
}
}
scanner.close();
double[] averages = calculateAverageScores(classScores);
int[] passedStudentsCount = calculatePassedStudents(classScores, averages); // 假定及格线为60分
for (int i = 0; i < 3; i++) {
System.out.println("第" + (i+1) + "班:");
System.out.printf("平均分:%.2f\n", averages[i]);
System.out.printf("及格人数:%d\n", passedStudentsCount[i]);
}
}
// 判断学号是否为三位数
private static boolean isValidStudentId(String studentId) {
return studentId.matches("\\d{3}");
}
// 计算平均分
private static double[] calculateAverageScores(String[][] scores) {
double[] averages = new double[scores.length];
for (String[] scoresRow : scores) {
if (scoresRow != null && scoresRow.length > 0) {
double sum = 0;
for (String scoreStr : scoresRow) {
int score = Integer.parseInt(scoreStr.split(",")[1]);
sum += score;
}
averages[scoresRow[0].split(",")[0].charAt(0)-'0'] = sum / scoresRow.length;
}
}
return averages;
}
// 计算及格人数
private static int[] calculatePassedStudents(String[][] scores, double[] averages) {
int[] passedStudents = new int[scores.length];
for (int i = 0; i < scores.length; i++) {
for (String scoreStr : scores[i]) {
if (Integer.parseInt(scoreStr.split(",")[1]) >= averages[i]) {
passedStudents[i]++;
break;
}
}
}
return passedStudents;
}
}
```
在这个Java程序中,我们首先导入了`Scanner`类以获取用户的输入,然后实现了数据录入、平均分计算和及格人数统计的功能。注意,这里假设了每个班级的学生编号是连续的,通过字符索引来对应平均分数组的位置。如果需要根据字母顺序调整,只需改变`calculateAverageScores`和`calculatePassedStudents`方法中计算索引的部分即可。
阅读全文