java - Scanner expects more input than is needed -


i'm having issue piece of code meant validate user input integer , between numbers 1-6.

the issue when add validation scanner waits input 3 times before continues. functions if don't include validation code. ideas why happening?

int level; boolean = false; double physact; system.out.print("on scale of 1 6, how active\ndo consider yourself?\n1 = lazy, 6 = pro athlete: "); system.out.flush(); while (!good){     if (!in.hasnextint()){         in.next();         system.out.print("sorry, must enter whole\nnumber between 1 , 6: ");     } else if ((in.nextint() < 0) || (in.nextint() > 7)){         in.next();         system.out.print("sorry, must enter whole\nnumber between 1 , 6: ");     } else {         = true;     } } level = in.nextint(); switch(level){     case 1:     physact = 1.2;         break; 

after switch goes on , used other operations.

your loop should read input once , remember mentioned. otherwise each call in.nextint() block until enter integer. keeping close same code need following.

while (!good){     if (!in.hasnextint()){         in.next();         system.out.print("sorry, must enter whole\nnumber between 1 , 6: ");     } else {         level = in.nextint();         if (level < 0 || level > 6) {             system.out.print("sorry, must enter whole\nnumber between 1 , 6: ");         } else {             = true;         }     } } 

remove level = in.nextint(); after loop since read in level.


Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -