Omar Qassem
Omar Qassem

Reputation: 107

Try Catch keeps looping instead of asking for another value?

I have the following code:

Scanner inputSide = new Scanner(System.in);

double side[] = new double[3];
int i = 0;
do{
    try{
    System.out.println("Enter three side lengths for a triangle (each followed by pressing enter):");
    side[i] = inputSide.nextDouble();
    i++;
    }
    catch(Exception wrongType){
        System.err.println(wrongType);
        System.out.println("Please enter a number.  Start again!!");
        i=0;
    }
}
while(i<3);

It works fine and does what it's meant to if I don't enter a wrong data type but if I enter something other than a double then it loops over and over, printing everything in both try and catch blocks instead of waiting for me to enter another double.

Any help as to why it's doing this - as I can't seem to understand why - would be appreciated.

Thank you :)

Upvotes: 0

Views: 661

Answers (1)

Rohit Jain
Rohit Jain

Reputation: 213261

The problem is that, you have used input.nextDouble method, which reads only the next token in the input, thus skipping the newline at the end. See Scanner.nextDouble

Now, if you enter wrong value first time, then it will consider the newline as the next input. Which will also be invalid.

You can add an empty input.nextLine in the catch block.

catch(Exception wrongType){
    System.err.println(wrongType);
    System.out.println("Please enter a number.  Start again!!");
    i=0;
    input.nextLine();  // So that it consumes the newline left over
}

Now, your nextLine() will read the linefeed left over, and linefeed will not be taken as input to your nextDouble next time. In which case, it will fail, even before you giving any input.

Upvotes: 3

Related Questions