我試圖做一個while循環,提示用戶在使用無效條目時重新輸入數據。在我的程序中,我要求用戶輸入一個數字(0-3),因此如果他們輸入了其他內容,我想要彈出一條錯誤消息,請他們重新輸入數據。我不知道我在循環中做錯了什麼。無論我輸入什麼,我都會收到錯誤信息。While循環問題(Java)
String itemChoice = JOptionPane.showInputDialog(null, itemList);
itemChoiceNum = Integer.parseInt(itemChoice);
//test to make sure the input is valid
while (itemChoiceNum != 0 || itemChoiceNum != 1 || itemChoiceNum != 2 || itemChoiceNum != 3) {
JOptionPane.showMessageDialog(null, "Sorry that's not a valid choice. Please start again.");
itemChoice = JOptionPane.showInputDialog(null, itemList);
}
NumberFormatException的
while (itemChoiceNum != 0 && itemChoiceNum != 1 && itemChoiceNum != 2 && itemChoiceNum != 3) {
try {
JOptionPane.showMessageDialog(null, "Sorry that's not a valid choice. Please start again.");
itemChoice = JOptionPane.showInputDialog(null, itemList);
itemChoiceNum = Integer.parseInt(itemChoice);
}
catch (NumberFormatException itemChoiceNum) {
JOptionPane.showMessageDialog(null, "Sorry that's not a valid choice. Please start again.");
}
錯誤
Exception in thread "main" java.lang.NumberFormatException: For input string: "f"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:492)
at java.lang.Integer.parseInt(Integer.java:527)
at VendingClass.displayVend(VendingClass.java:82)
at VendingMachineDemo.main(VendingMachineDemo.java:12)
就是這樣!謝謝! – 2013-05-07 19:51:34
跟進,如果用戶輸入一個字符串,有沒有辦法顯示錯誤信息?當我輸入一個字符串時,程序崩潰。 – 2013-05-07 20:51:57
捕獲'Integer.parseInt'拋出的'NumberFormatException'並向用戶顯示一條適當的錯誤消息的消息對話框。 – rgettman 2013-05-07 20:53:59