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)
?