编写一个程序,用于输入某个班级某门课程的检测成绩,并计入及格人数、不及格人数、课程平均分,为了处理输入成绩的不合理情况(成绩大于100或小于0),设计一个自定义的异常类,当检测到这种无效成绩时抛出异常,用Java的语言
时间: 2024-11-29 20:32:49 浏览: 56
在Java中,你可以编写一个简单的控制台应用程序来满足这个需求。首先,我们需要创建一个`StudentScoreException`自定义异常类,用于捕获和处理无效的成绩:
```java
public class StudentScoreException extends Exception {
public StudentScoreException(String message) {
super(message);
}
}
```
接下来,定义一个`CourseGrade`类,用于存储数据并计算统计信息:
```java
import java.util.ArrayList;
import java.util.List;
public class CourseGrade {
private String courseName;
private List<Integer> scores = new ArrayList<>();
public void addScore(int score) throws StudentScoreException {
if (score < 0 || score > 100) {
throw new StudentScoreException("Invalid score! Score must be between 0 and 100.");
}
scores.add(score);
}
public int getPassingCount() {
return scores.stream().filter(score -> score >= 60).count();
}
public int getFailingCount() {
return scores.size() - getPassingCount();
}
public double calculateAverage() {
if (scores.isEmpty()) {
return 0;
}
return scores.stream().mapToInt(Integer::intValue).average().orElse(0);
}
}
```
然后在主函数中接受用户输入并使用`CourseGrade`类:
```java
public static void main(String[] args) {
CourseGrade mathGrade = new CourseGrade();
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the course name:");
String courseName = scanner.nextLine();
while (true) {
System.out.println("Enter a student's score (or 'done' to finish):");
int score = scanner.nextInt();
try {
mathGrade.addScore(score);
} catch (StudentScoreException e) {
System.out.println(e.getMessage());
}
if (scanner.next().equals("done")) break;
}
System.out.println("\nResults for " + courseName + ":");
System.out.println("Passing students: " + mathGrade.getPassingCount());
System.out.println("Failing students: " + mathGrade.getFailingCount());
System.out.println("Average score: " + mathGrade.calculateAverage());
}
```
在这个程序中,用户可以输入每个学生的分数,直到他们输入"done"为止。如果输入的分数不在有效范围内,会抛出`StudentScoreException`。
阅读全文
相关推荐
















