2、编写程序接收用户输入分数信息,如果分数在0—100之间, 输出成绩。如果成绩不在该范围内, 抛出异常信息,提示分数必须在0—100之间。
要求:使用自定义异常实现
1 import java.util.Scanner;
2
3 class AtException extends RuntimeException {
4 public AtException(String msg) {
5 super(msg);
6 }
7 }
8 public class Exception_02 {
9 public static void main(String[] agre) throws AtException {
10 Scanner a = new Scanner(System.in);
11 System.out.println("请输入你的成绩:");
12 input(a);
13 }
14 public static void input(Scanner a) throws AtException {
15 while (true) { //可以多次输入成绩
16 double in = a.nextDouble();//将输入的字符串转变为双精度类型数据类型
17 if (in >= 0 && in <= 100) { //在0~100内,则正常输出成绩
18 System.out.print(in);
19 } else {//不在范围内,则抛出异常
20 AtException i = new AtException("你输入的:" + in + "为非法成绩,"
21 + "请输入正确的成绩!");
22 throw i;
23 }
24 }
25
26 }
27 }
运行结果:
1 请输入你的成绩: 2 90 3 90.0 4 101 5 Exception in thread "main" Exception_and_Multithreading.AtException: 你输入的:101.0为非法成绩,请输入正确的成绩! 6 at Exception_and_Multithreading.Exception_02.input(Exception_02.java:26) 7 at Exception_and_Multithreading.Exception_02.main(Exception_02.java:18)