Reputation: 111
I'm trying to make a while loop that prompts the user to re-enter data if they use an invalid entry. In my program I'm asking the user to input a number(0-3), so if they enter anything other than that I want an error message to pop up, asking them to re-enter their data. I don't know what I'm doing wrong in my loop. No matter what I enter I always get the error message.
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.");
}
Error
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)
Upvotes: 1
Views: 199
Reputation: 121998
Use should &&
instead ||
in the while condition.As of now it always returns True.
Upvotes: 1
Reputation: 178263
Your logic is incorrect. It's always true that the choice isn't 0 or it isn't 1 or it isn't 2; you want "and" with the &&
operator.
while (itemChoiceNum != 0 && itemChoiceNum != 1 && itemChoiceNum != 2 && itemChoiceNum != 4) {
Upvotes: 6