我正在嘗試創建一個switch語句,將月份作爲整數,並基於該整數,我想輸出月份名稱。由於某些我不知道的原因,case '10'
給了我一個無效的字符常量錯誤信息。有誰知道爲什麼會發生這種情況,我該如何解決這個問題?謝謝你,代碼如下:開關語句:無效的字符常量
switch (month) {
case "1": System.out.println("January");
break;
case "2": System.out.println("February");
break;
case "3": System.out.println("March");
break;
case "4": System.out.println("April");
break;
case "5": System.out.println("May");
break;
case "6": System.out.println("June");
break;
case "7": System.out.println("July");
break;
case "8": System.out.println("August");
break;
case "9": System.out.println("September");
break;
case "10": System.out.println("October");
break;
case "11": System.out.println("November");
break;
case "12": System.out.println("December");
break;
}
更多的答案後:
switch (month) {
case '1': System.out.println("January");
break;
case '2': System.out.println("February");
break;
case '3': System.out.println("March");
break;
case '4': System.out.println("April");
break;
case '5': System.out.println("May");
break;
case '6': System.out.println("June");
break;
case '7': System.out.println("July");
break;
case '8': System.out.println("August");
break;
case '9': System.out.println("September");
break;
case '10': System.out.println("October");
break;
case '11': System.out.println("November");
break;
case '12': System.out.println("December");
break;
}
答案後
switch (month) {
case 1: System.out.println("January");
break;
case 2: System.out.println("February");
break;
case 3: System.out.println("March");
break;
case 4: System.out.println("April");
break;
case 5: System.out.println("May");
break;
case 6: System.out.println("June");
break;
case 7: System.out.println("July");
break;
case 8: System.out.println("August");
break;
case 9: System.out.println("September");
break;
case 10: System.out.println("October");
break;
case 11: System.out.println("November");
break;
case 12: System.out.println("December");
break;
}
'10'不是一個字符。這顯然是兩個字符。在執行'switch' /'case'之前,將字符轉換爲'int'。使用字符串的 – 2014-09-19 02:46:29
在你的情況下是完全不必要的。所有你需要的是12個整數,所以只需使用整數:) – nem035 2014-09-19 02:48:42
我決定讓月份成爲一個字符串並使用雙引號「」。感謝大家!!!! – pbars23 2014-09-19 02:50:25