3 回答

TA貢獻1818條經驗 獲得超11個贊
包裹
choiceofcake = Integer.parseInt(userinput);
嘗試捕捉
try {
choiceofcake = Integer.parseInt(userinput);
if (choiceofcake > 5 || choiceofcake < 1) {
break;
}
} catch (NumberFormatException ee) {
ee.printStatckTrace ();
continue;
}

TA貢獻1829條經驗 獲得超4個贊
由于您是 Java 新手,因此 try-catch 的想法是在可能發生異常的情況下包圍一段代碼。在您的情況下,如果“userInput”無法轉換為數字,“parseInt”可能會引發異常??梢詤⒖脊俜轿臋n發現哪些異常類型: https://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#parseInt(java.lang.String)
您還可以創建和/或拋出您自己的異常。例如,在這種情況下,您可以在檢查“userInput”是否超出所需值后引發 IllegalArgumentException:
throw new IllegalArgumentException();
您可以在某處捕獲異常,然后顯示帶有警報的消息對話框。

TA貢獻1802條經驗 獲得超6個贊
假設您希望循環繼續,即使在輸入錯誤的情況下,您也可以嘗試以下操作:
do {
String userinput = JOptionPane.showInputDialog(null, "Enter your choice of cake:" +
"\n" + "1." + Cakes[0].getflavorofcake() + "(" + Cakes[0].getpriceofcake() + "cents" + ")" + " no. of cakes available:" + Cakes[0].getnofcaksleft() +
"\n" + "2." + Cakes[1].getflavorofcake() + "(" + Cakes[1].getpriceofcake() + "cents" + ")" + " no. of cakes available:" + Cakes[1].getnofcaksleft() +
"\n" + "3." + Cakes[2].getflavorofcake() + "(" + Cakes[2].getpriceofcake() + "cents" + ")" + " no. of cakes available:" + Cakes[2].getnofcaksleft() +
"\n" + "4." + Cakes[3].getflavorofcake() + "(" + Cakes[3].getpriceofcake() + "cents" + ")" + " no. of cakes available:" + Cakes[3].getnofcaksleft() +
"\n" + "5." + Cakes[4].getflavorofcake() + "(" + Cakes[4].getpriceofcake() + "cents" + ")" + " no. of cakes available:" + Cakes[4].getnofcaksleft(), "mini cake shop", JOptionPane.QUESTION_MESSAGE);
choiceofcake = Integer.parseInt(userinput);
if (choiceofcake > 5 || choiceofcake < 1) {
JOptionPane.showMessageDialog(null, "Invalid input! Please enter in the range from 1 to 5", "Error", JOptionPane.ERROR_MESSAGE);
}
else {
showthatthereisnocakesleft(choiceofcake);
}
} while (Cakes[choiceofcake - 1].getnofcaksleft() < 1);
如果您希望循環在輸入錯誤時完全停止,請考慮IllegalArgumentException在發生這種情況時拋出一個。
添加回答
舉報