Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Java 多型與例外處理:成績等級判斷的健壯性寫法

題目:撰寫一個程式,讓使用者輸入某門課的考試成績(整數),程式接著給出「不及格」、「及格」、「中」、「良」、「優」的結論。關鍵要求是有足夠的健壯性——不管使用者輸入什麼,程式都不能崩潰。

import java.util.*;

public class Mark {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int score = 0;
        System.out.print("請輸入成績:");

        try {
            score = sc.nextInt();

            if (score >= 0 && score <= 59) {
                System.out.println("不及格");
            }
            if (score >= 60 && score <= 69) {
                System.out.println("及格");
            }
            if (score >= 70 && score <= 79) {
                System.out.println("中");
            }
            if (score >= 80 && score <= 89) {
                System.out.println("良");
            }
            if (score >= 90 && score <= 100) {
                System.out.println("優");
            }
            if (score < 0 || score > 100) {
                System.out.println("輸入的數字過大或過小");
            }
        } catch (Exception e) {
            System.out.println("請輸入正確數字:");
        }
    }
}

這裡的健壯性來自兩層防護:一是 try/catch 攔住 nextInt() 遇到非數字輸入時拋出的例外,避免程式直接結束;二是用 if 逐段過濾範圍,超出 0–100 的數字會得到明確提示。

若進一步優化,可以把這串 if 改成 else if 或 switch 表達式,讓分支互斥、可讀性更好;也可以自訂例外處理超出範圍的情況,讓「輸入錯誤」與「輸入越界」的回饋更精準。

Copyright © Linux教程網 All Rights Reserved