0

I am trying to do a chess game and at a certain point the user inputs a number relating to what piece they want to move. I had a simplified version of the code below earlier, but I recently decided to put a 'try' and 'catch' statement to catch the InputMismatchException. This is the code:

int inputexception = 0;

do {

    inputexception = 0;

    try {

        System.out.println("What piece would you like to move?");           
        pieceselectioninput = scan.nextInt();

    } catch ( InputMismatchException e ){

        inputexception = 1;

    }

} while ( inputexception == 1 );

So once I run this program, if I input a non-Int value, it repeats on and on forever with "What piece would you like to move?" being displayed on the screen continuously until I manually terminate the program.

What am I doing wrong? It wasn't like this until I added the 'try' and 'catch' phrases.

Benjamin Lowry
  • 3,730
  • 1
  • 23
  • 27
  • You could go with [`Scanner#nextLine`](http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextLine()) and try to check wether the input matches a number only input and cast it afterwards – SomeJavaGuy Aug 03 '15 at 07:59
  • Have you tried to use a debugger to find out what is wrong? – Jens Aug 03 '15 at 08:01
  • @Jens yes, I have. What looks like the problem to me is that the scanner isn't waiting for me to reply, and I don't know why – Benjamin Lowry Aug 03 '15 at 08:08
  • possible duplicate of [\[Infinite Loop\]Try.. catch with exceptions](http://stackoverflow.com/questions/3572160/infinite-looptry-catch-with-exceptions) – Tom Aug 03 '15 at 08:48

2 Answers2

1

You run the while-loop as long as inputexception == 1, and you set the inpuexception value to 1 in the catch block of the InputMismatchException. This makes the loop continue every time you type a non int value.

ghdalum
  • 891
  • 5
  • 17
  • Yeah, I did that so that if it isn't an 'int', the user will have to input again, but the scanner doesn't allow time for the user to input another piece, it just continues on forever. – Benjamin Lowry Aug 03 '15 at 08:03
0

There are two solutions to your problem:

keep nextInt

int inputexception = 0;

do {
   inputexception = 0;

   try {

       System.out.println("What piece would you like to move?");           
       pieceselectioninput = scan.nextInt();

    } catch ( InputMismatchException e ){
        // Get the next line so it won´t repeat forever
        scan.nextLine();
        inputexception = 1;
    }
} while ( inputexception == 1 );

Directly use the nextline Statement with parsing:

int inputexception = 0;

do {

inputexception = 0;

    try {

        System.out.println("What piece would you like to move?");     
        String input = scan.nextLine();
        pieceselectioninput = Integer.parseInt(input);

    } catch ( NumberFormatException e ){
        inputexception = 1;
    }
} while ( inputexception == 1 );
SomeJavaGuy
  • 7,307
  • 2
  • 21
  • 33