題目:利用條件運算符的嵌套來完成此題:學習成績>=90 分的同學用 A 表示,60-89 分之間的用 B 表示,
60 分以下的用 C 表示。
程序分析:(a>b)?a:b 這是條件運算符的基本例子。
1 import java.util.*; 2 3 public class Test5 { 4 5 public static void main(String[] args) { 6 Scanner in = new Scanner(System.in); 7 //輸入分數 8 System.out.println("請輸入你的分數:"); 9 int num = in.nextInt(); 10 in.close(); 11 grade(num); 12 } 13 14 private static void grade(int n) { 15 if(n>100||n<0) 16 { 17 System.out.println("輸入錯誤,請輸入正確的成績!"); 18 } 19 else 20 { 21 String s = (n>=90) ? "等級為A" : (n>=60) ? "等級為B" : "等級為C"; 22 System.out.println(s); 23 } 24 } 25 26 }