輸入分數 N:
import javax.swing.JOptionPane;
public class GradeClassifier {
public static void main(String[] args) {
String input = JOptionPane.showInputDialog("請輸入分數 (0-100):");
if (input == null) return; // 使用者按取消
try {
int score = Integer.parseInt(input.trim());
if (score < 0 || score > 100) {
JOptionPane.showMessageDialog(null, "分數超出範圍");
return;
}
String grade = (score >= 90) ? "A" : (score >= 60) ? "B" : "C";
System.out.println("等級:" + grade);
JOptionPane.showMessageDialog(null, "成績等級:" + grade);
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null, "請輸入有效整數");
}
}
}
condition1 ? value1 : (condition2 ? value2 : value3)
a ? b : c ? d : e 等同 a ? b : (c ? d : e)。| 寫法 | 優點 | 缺點 |
|---|---|---|
| 巢狀三元 | 單行、表達式、無副作用 | 層級深時難讀 |
| if-else if | 清晰、易除錯、可加日誌 | 佔行數多 |
| Switch (Java 12+) | 表達式、型別安全 | 需較新 Java 版本 |
| 查表法 (Map/陣列) | O(1)、資料驅動、易擴充 | 區間型條件需額外邏輯 |