我正在尝试创建一个 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)