我正在尝试制作一个 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);
}
数字格式异常
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)
最佳答案
你的逻辑不正确。选择不是 0 或 它不是 1 或 它不是 2 总是正确的;您想要使用 &&
运算符的“和”。
while (itemChoiceNum != 0 && itemChoiceNum != 1 && itemChoiceNum != 2 && itemChoiceNum != 4) {
关于java - While 循环问题(Java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16427315/