java - Error catching with try-catch and while loop -
this question has answer here:
i'm trying make sure users input integer when use below code infinite loop of print
statement. advice of how improve?
boolean valid = false; system.out.println("what block gathering? (use minecraft block ids)"); while(valid == false){ try{ block = input.nextint(); valid = true; } catch(inputmismatchexception exception){ system.out.println("what block gathering? (use minecraft block ids)"); valid = false; } }
nextint()
doesn't consume invalid input try read same invalid value on , on again. solve problem need consume explicitly calling next()
or nextline()
accept value.
btw make code cleaner , avoid expensive operations creating exceptions should use methods hasnextint()
.
here how can organize code
system.out.println("what block gathering? (use minecraft block ids)"); while(!input.hasnextint()){ input.nextline();// consume invalid values until end of line, // use next() if want consume them 1 one. system.out.println("that not integer. please try again"); } //here sure next element int, lets read block = input.nextint();
Comments
Post a Comment