1

I am currently working on some Java code in Eclipse and trying to use a try-catch statement inside of a do-while statement. My current code is as follows:

import java.util.Scanner;
import java.util.InputMismatchException;
import java.util.Random;
public class GG_HighLowInvalid{

    public static void main(String[] args){

        Scanner cg = new Scanner(System.in);

        //Assign and define variables
        int guess, rand;
        guess = 0;
        rand = 10;

        //Create loop
        do 
            try{
                guess = 0;
                //Ask for a guess
                System.out.print("Enter your guess: ");

                //Record the guess
                guess = cg.nextInt();
            }
            catch(InputMismatchException exception){

                System.out.println("Your guess must be an integer.");

            }
        while  (guess != rand);


    }
}

When I put in any number, the code works fine and will loop to ask for another input and when 10 is entered, the code stops as it is supposed to (because guess becomes equal to rand). However, if I put in anything that is not an integer (such as "No"), an infinite loop occurs where the output prints the following:

"Your guess must be and integer."

"Enter your Guess: Your guess must be an integer."

"Enter your Guess: Your guess must be an integer."

"Enter your Guess: Your guess must be an integer."

repeating forever until the program is externally terminated.

Since the while statement is (guess != rand), why is a non-integer causing this infinite loop? Shouldn't the manual input under the try-statement be called again? Any assistance in understanding this would be greatly appreciated. Also, I am pretty new to Java, so sorry in advance if I am having simple issues.

Scott T
  • 233
  • 2
  • 5
  • 14
  • have you tried to use debugger to see value of `guess` and `rand` when it evaluated by `while` condition? – Anatoly Sep 19 '15 at 10:04
  • The fact that you enter a non-integer does not impact the fact that `guess` is an `int` anyway, with a value of `0` (or the one of your latest guess). Therefore, `guess != rand` still holds if it held before. The real issue, however, is that the `Scanner` object keeps reading the same input without asking for a new one. This is addressed by @TAsk's answer. – Eusebius Sep 19 '15 at 10:09

4 Answers4

4

When a scanner throws an InputMismatchException, the scanner will not pass the token that caused the exception, so that it may be retrieved or skipped via some other method.

Currently, your Scanner is not moving ahead to read the next input but reading the same continuously. You have to explicitly call some method which can read this incorrect value which was not expected. For example, scanner.next() call in catch block can avoid this infinite loop.

akash
  • 22,664
  • 11
  • 59
  • 87
  • 1
    Thank you, this helped tremendously as I did not know that scanners functioned in that manner! I will come back in 5 minutes when I can accept an answer and make sure to mark yours as correct. – Scott T Sep 19 '15 at 10:11
  • @ScottT If you run into problems, it is always advisable to study the Javadoc of the classes involved. This is documented for [`Scanner`](http://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html) – Mark Rotteveel Sep 19 '15 at 10:41
1

You dont need to use a try catch statement. You just have to check if it is an integer or not with the hasNextInt() method of your object scanner. This is an example, it will solve your problem:

public static void main(String[] args) {
    Scanner cg = new Scanner(System.in);
    boolean valid = false;
    //Assign and define variables
    int guess, rand;
    guess = 0;
    rand = 10;

    //Create loop
    do{
        System.out.println("Enter your guess: ");
        if(cg.hasNextInt()){
            guess = cg.nextInt();  
            valid = true;
        }else{
            System.out.println("Your guess must be an integer.");
            cg.next();
        }
    }while  (!valid || guess != rand);
}
Yassine.b
  • 617
  • 5
  • 11
1

Use the following code:

       catch(InputMismatchException exception){
                cg.next();
                System.out.println("Your guess must be an integer.");

       }

After you have unsuccessfully read buffer its value isn't emptied and next time when it came to cg.nextInt() it tries to read same wrong value, and you went to loop. You need "to empty buffer", so next time it will read correct value.

Anatoly
  • 5,056
  • 9
  • 62
  • 136
-2

Try resetting your variable "guess = 0" in catch block.

Darshan
  • 515
  • 1
  • 3
  • 16