java - Invalid input still updates the total -
[edit] seems moving piece of code somewhere else solve issue, can't see figure out where..
if (numleaving < min_people || numentering < min_people || totalpeople < min_people) { joptionpane.showmessagedialog(null,"invalid data"); }
could explain why 'total people' still gets updated when enter invalid value such negative number? also, why total people printed anyway if user enters invalid input?
final int max_people = 65; final int min_people = 0; int totalpeople = 0; int numleaving = 0; int numentering = 0; boolean invalid = true; while (invalid) { string question = joptionpane.showinputdialog("leaving or entering?"); try { // decrease total if people leaving if (question.equalsignorecase("leaving")) { numleaving = integer.parseint(joptionpane.showinputdialog("number leaving:")); totalpeople -= numleaving; } // increase total if people entering else if (question.equalsignorecase("entering")) { numentering = integer.parseint(joptionpane.showinputdialog("number entering:")); totalpeople += numentering; } else { joptionpane.showmessagedialog(null,"'leaving' or 'entering' only"); } // prints out current total before capacity exceeded if (totalpeople > max_people) { invalid = false; totalpeople = totalpeople - numentering; joptionpane.showmessagedialog(null,"capacity exceeded\n" + "total people = " + totalpeople); } else { joptionpane.showmessagedialog(null,"total people = " + totalpeople); } } catch (numberformatexception e) { joptionpane.showmessagedialog(null,"numbers only"); } }
the reason 'totalpeople' still being updated because not checking if valid input in beginning loop. if add following code in beginning of while loop:
if(totalpeople < 0){ invalid = false; break; }
also find bit misleading naming boolean in negative. having boolean named 'invalid' being true make 1 question, "does true stand valid or invalid?"
i name boolean 'valid' instead.
Comments
Post a Comment