Problem Description
1.实验目的
(1) 熟悉异常的抛出与捕获的含义;
(2) 掌握异常捕获与处理的方法;
(3) 能自定义异常。
2.实验内容
编写成绩管理应用程序,其中有成绩录入模块,成绩录入过程中,录入的成绩不在合理的范围(比如小于0或者大于100),若出现上述错误,程序抛出异常(小于0抛出异常打印negative,大于100抛出异常打印 too high)。
3.实验要求
请将下列代码补充完整
import java.util.*;
public class Main{
public static void main(String arg[])
{
ExceptionDemo demo = new ExceptionDemo();
demo.inputScore();
}
}
// 你的代码
Input Description
Output Description
Sample Input
59,45,78,-10,39,62,130
Sample Output
negative
too high
Hint
我的想法:
我的代码:
package com.zuoye.Main;
import java.util.Scanner;
public class Main {
public static void main(String arg[]) {
ExceptionDemo demo = new ExceptionDemo();
demo.inputScore();
}
}
// 你的代码
class ExceptionDemo {
public ExceptionDemo() {
}
public void inputScore() {
Scanner scanner = new Scanner(System.in);
/*读取成绩*/
String[] split = scanner.nextLine().split(",");
for (String s : split) {
int grade = Integer.parseInt(s);
if (grade < 0) {
try {
throw new ExceptionCode("negative");
} catch (ExceptionCode e) {
System.out.println(e.getMessage());
}
}
if (grade > 100) {
try {
throw new ExceptionCode("too high");
} catch (ExceptionCode e) {
System.out.println(e.getMessage());
}
}
}
}
}
class ExceptionCode extends Exception {
/**
* 空参构造
*/
public ExceptionCode() {
}
/**
* @param message 表示异常提示
*/
public ExceptionCode(String message) {
super(message);
}
}