Reputation: 947
I have to validate my user input for an integer value and prompt the user to reenter if an invalid value is entered. Thus far I have put together this method below. i believe the logic is correct but I need to get the user to reenter input again after the error message.
void validateItemquantity() {
boolean error = true;
while (error) {
try{
Integer.parseInt(itemQuantityinput.getText());
error = false;
}
catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null, "Item quantity must be a positive number, please reenter");
error = true;
}
}
}
Part of code from jframe method:
private void bnPurchaseActionPerformed(java.awt.event.ActionEvent evt) {
String itemCode;
int itemQuantity, itemPrice, itemCost, totalCost ;
validateItemquantity();
itemCode = itemCodeinput.getText();
itemQuantity = Integer.parseInt(itemQuantityinput.getText());
itemPrice = catalog.searchCatalog(itemCode);
itemCost = payment.calculateItemcost(itemQuantity,itemPrice);
totalCost = payment.calculateTotalcost(itemCost);
Upvotes: 0
Views: 1544
Reputation: 2621
If the user enters a wrong value your method would loop endlessly. If the method does not wait for the JOptionPane to close you will be confronted with an immesurable amount of dialog-popups.
You should let the method return a boolean value in any case and change some kind of "state", another boolean or some other kind of state-variable, in your programm if it succeeds.
If it doesn't you can let your state "loop" back to the point where the user has to enter a number and then let him restart the validation process, but in my opinion you should not restart the validation process on it's own when it fails.
Upvotes: 1
Reputation: 46788
The validateItemquantity()
method should return a true or false, based on whether the input is valid or not.
You can take care of the true and false cases in the function calling it. To take input, you could show an input dialog maybe.
String text = JOptionPane.showInputDialog ("Enter New Value"));
Upvotes: 2
Reputation: 8718
I think the loop should be in the calling method.
boolean validateItemquantity() {
try{
Integer.parseInt(itemQuantityinput.getText());
return true;
}
catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null, "Item quantity must be a positive number, please reenter");
error = false;
}
}
And the calling part should be something like that
while(!validateItemquantity())
Upvotes: 1