Reputation: 3789
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.
Upvotes: 0
Views: 102
Reputation: 7347
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 );
Upvotes: 0
Reputation: 891
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.
Upvotes: 1