I am trying to execute a bit of code that scans for a user input value. This action is contained in a custom method I wrote, named getTriangleDim(); the method reads in the users int value, makes sure it is within a certain range, and then returns the int value that was entered. The method works great and I have no issues with it.
The problem arises when I enter a non-int value for my getTriangleDim() method. It gives me an InputMismatchException error. I have written a try-catch statement into a do-while loop to attempt to fix this issue. But this is the first time I have ever used a try-catch statement, and I am apparently missing something.
Here is the code for the try-catch statement nested within the do-while loop:
//loop to scan for triangle dimension
boolean bError = true;
int triangle;
do{
try {
triangle = getTriangleDim();
bError=false;
}
catch (Exception e){
System.out.println("You did not enter an integer, please enter an integer value");
triangle = getTriangleDim();
}
}while (bError);
if i test it by entering a char value in place of the int, it actually catches the error once, and then prints my "you did not....." statement. But if I re-enter another non-int number, I get a runtime error again that says.......you guessed it........ InputMismatchException error.
The code for my method is here:
//method for scanning triangle dimensions from keyboard
public static int getTriangleDim(){
int triangle = 0;
Scanner keyboard = new Scanner(System.in);
do{
System.out.print("Enter a non-zero integer length (+/-1 - +/-16): ");
triangle = keyboard.nextInt();
if((!(triangle <= 16 && triangle >= 1))&&(!(triangle >= -16 && triangle <= -1)))
System.out.println("Inpute value outside of range");
}while((!(triangle <= 16 && triangle >= 1))&&(!(triangle >= -16 && triangle <= -1)));
return triangle;
}
I need the Do-While loop to continue, but I keep getting these errors.
class NotIntegerException extends Exception { .. }
and catch it outside, to distinguish it from other type of exceptions – Khaled.K