6

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.

  • You can define a new Exception `class NotIntegerException extends Exception { .. }` and catch it outside, to distinguish it from other type of exceptions – Khaled.K Feb 25 '14 at 05:07

1 Answers1

2

There's no need to ask for input in the catch block. You're already in a loop, so you can catch the exception, tell the user to give you valid input, and then you don't have to do anything else--you'll loop back around to the beginning.

do{
    try {
        triangle = getTriangleDim();
        bError=false;
    } catch (Exception e){
        System.out.println("You did not enter an integer, please enter an integer value");
        // Don't do anything else in here: we will loop back to the beginning again and get new input!
    }
}while (bError);

As a side note (and as you've noticed), your code won't currently compile if you try to use triangle outside of that try block, because "triangle might not have been initialized". This is due to the fact that the compiler cannot determine at compile-time what your program will do at run-time: that is, the compiler cannot see that triangle will always be initialized within that loop. So your variable declaration ought to also set triangle to some default value. 0 is the normal default for int, but use whatever makes sense in your program (it looks like 0 is fine, based on your getTriangleDim code).

int triangle = 0;
do { // etc.

This way you can "promise" the compiler that triangle will have a value by the time you leave the loop, and you'll be able to use it elsewhere.

Henry Keiter
  • 16,863
  • 7
  • 51
  • 80
  • thanks, I feel silly now. I updated my code to remove the scanner input in the catch block. But now I am getting a different error, the compiler is giving me the following error "Uncompilable source code - variable triangle might not have been initialized". Also, after my Do-while loop and nested try-catch statements, every reference to the traingle variable is underlined in red. I don't understand, it seems as if my program doesn't recognize that it has been initialized with a value? –  Feb 25 '14 at 05:00
  • 1
    @Adam The compiler doesn't lie! *You* can see that it should be initialized by the time you exit the loop, but the compiler [can't predict how your program will run](http://en.wikipedia.org/wiki/Halting_problem). As far as the *compiler's* concerned, you might be able to leave the loop without initializing `triangle`. See [this question](http://stackoverflow.com/q/14790940/2069350) for an example similar to yours, but the point is that you must initialize `triangle` to some default value (`0` and `-1` are common) *before* the loop where you do the real assignment (e.g. `int triangle = 0;`). – Henry Keiter Feb 25 '14 at 05:32
  • Thnaks! I appreciate the help. –  Feb 25 '14 at 14:18