I trying to understand why the method validateItemquantity eventually crashes with an NumberFormatException error. The logic seem correct, but something is not right. Its suppose to keep asking the user to reenter until it gets an valid input and then return that valid input.
String validateItemquantity(String itemQuantity) {
try{
Integer.parseInt(itemQuantity);
}
catch (NumberFormatException e) {
itemQuantity = JOptionPane.showInputDialog
("Invalid item quantiy, please enter a new Value");
validateItemquantity(itemQuantity);
}
return itemQuantity ;
Method that calls it:
private void bnPurchaseActionPerformed(java.awt.event.ActionEvent evt) {
String itemCode, validItemquantity ;
int itemQuantity, itemPrice, itemCost, totalCost ;
validItemquantity = validateItemquantity(itemQuantityinput.getText());
itemQuantity = Integer.parseInt(validItemquantity);
itemCode = itemCodeinput.getText();
itemPrice = catalog.searchCatalog(itemCode);
itemCost = payment.calculateItemcost(itemQuantity,itemPrice);
totalCost = payment.calculateTotalcost(itemCost);
Have it return the result of the parse or call itself on exception, like this:
This method will only return a valid response; it loops forever until it gets a valid response.
A few comments have mentioned that the above code may be attacked by the user entering bad data millions of times and blowing the stack. I say “let them”, but if you really want to make it safe, use a while loop:
It adds a
whileloop, so the code complexity increases slightly, but it’s only couple of extra lines of code and it is more efficient and safe.