我正在尝试创建一个while循环,提示用户在使用无效条目时重新输入数据 . 在我的程序中,我要求用户输入一个数字(0-3),所以如果他们输入除此之外的任何内容,我想要弹出一条错误消息,要求他们重新输入他们的数据 . 我不知道我在循环中做错了什么 . 无论我输入什么,我总是收到错误消息 .
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)
2 回答
在while条件中使用
&&
而不是||
. 截至目前,它始终返回True .你的逻辑不正确 . 它's always true that the choice isn' t 0或它不是1或它不是2;你想"and"与
&&
运算符 .