练习-java异常处理之throw之学生总成绩
·
下面是一个新的练习程序,仍然聚焦于 Java 中的 throw 和异常处理。这次扩展内容为处理多个科目的成绩,并计算总成绩时抛出异常。
示例代码:多个科目的成绩处理
// 自定义异常类:用于单科成绩的异常
class InvalidScoreException extends Exception {
public InvalidScoreException(String message) {
super(message);
}
}
// 学生类
class Student {
private String name;
private int[] scores; // 各科成绩
private int totalScore; // 总成绩
// 构造方法
public Student(String name, int[] scores) throws InvalidScoreException {
this.name = name;
setScores(scores);
}
// 设置成绩的方法
public void setScores(int[] scores) throws InvalidScoreException {
this.scores = new int[scores.length];
totalScore = 0;
for (int i = 0; i < scores.length; i++) {
if (scores[i] < 0 || scores[i] > 100) {
throw new InvalidScoreException("科目 " + (i + 1) + " 的成绩无效!成绩必须在 0 到 100 之间,当前输入: " + scores[i]);
}
this.scores[i] = scores[i];
totalScore += scores[i];
}
}
// 显示学生信息
public void displayStudentInfo() {
System.out.println("学生姓名: " + name);
System.out.print("各科成绩: ");
for (int score : scores) {
System.out.print(score + " ");
}
System.out.println("\n总成绩: " + totalScore);
}
}
// 测试类
public class Main {
public static void main(String[] args) {
try {
// 测试正常数据
int[] scores1 = {85, 90, 78};
Student student1 = new Student("张三", scores1);
student1.displayStudentInfo();
// 测试异常数据
int[] scores2 = {88, 105, 76}; // 第二科成绩无效
Student student2 = new Student("李四", scores2);
student2.displayStudentInfo();
} catch (InvalidScoreException e) {
System.err.println("捕获异常: " + e.getMessage());
}
}
}
代码说明
-
多个科目的成绩验证:
- 使用数组存储各科成绩,并在
setScores方法中逐一检查每个成绩是否在 0 到 100 范围内。 - 如果有任何一个成绩无效,抛出
InvalidScoreException。
- 使用数组存储各科成绩,并在
-
总成绩计算:
- 在
setScores方法中,逐一累加有效成绩,计算总成绩。
- 在
-
异常捕获:
- 在
main方法中,通过try-catch块捕获无效成绩的异常,并输出错误信息。
- 在
输出示例
正常数据
学生姓名: 张三
各科成绩: 85 90 78
总成绩: 253
异常数据
捕获异常: 科目 2 的成绩无效!成绩必须在 0 到 100 之间,当前输入: 105
练习价值
-
强化
throw的使用:- 每次遇到无效输入时,抛出异常,以确保数据的有效性。
-
多样化异常场景:
- 在多个字段或数组中处理异常,通过循环和校验更贴近真实开发中的需求。
-
更清晰的异常信息:
- 异常信息带有具体的科目和错误原因,便于调试和定位问题。
你可以尝试添加更多功能,比如支持动态输入、计算平均分等,进一步完善程序。
更多推荐
所有评论(0)