java - Scanner skipping over user input -


i trying chess game , @ point user inputs number relating piece want move. had simplified version of code below earlier, decided put 'try' , 'catch' statement catch inputmismatchexception. code:

int inputexception = 0;  {      inputexception = 0;      try {          system.out.println("what piece move?");                    pieceselectioninput = scan.nextint();      } catch ( inputmismatchexception e ){          inputexception = 1;      }  } while ( inputexception == 1 ); 

so once run program, if input non-int value, repeats on , on forever "what piece move?" being displayed on screen continuously until manually terminate program.

what doing wrong? wasn't until added 'try' , 'catch' phrases.

there 2 solutions problem:

keep nextint

int inputexception = 0;  {    inputexception = 0;     try {         system.out.println("what piece move?");                   pieceselectioninput = scan.nextint();      } catch ( inputmismatchexception e ){         // next line won´t repeat forever         scan.nextline();         inputexception = 1;     } } while ( inputexception == 1 ); 

directly use nextline statement parsing:

int inputexception = 0;  {  inputexception = 0;      try {          system.out.println("what piece move?");              string input = scan.nextline();         pieceselectioninput = integer.parseint(input);      } catch ( numberformatexception e ){         inputexception = 1;     } } while ( inputexception == 1 ); 

Comments

Popular posts from this blog

python - Healpy: From Data to Healpix map -

c - Bitwise operation with (signed) enum value -

xslt - Unnest parent nodes by child node -