Home > database >  Java Try/Catch loops indefinitely in recursive method [duplicate]
Java Try/Catch loops indefinitely in recursive method [duplicate]

Time:09-27

I am trying to run a PowerShell input in Java with a recursive function, Scan(), but the Try/Catch, once triggered, loops until I get an overflow error. The try/catch is there to catch Exception errors from a type error for the input. If the type int is not met, the catch catches the Exception and reruns the function, but it doesn't pause for new inputs it just loops. How can I prevent this? Code below:

//when called, runs a new scan request through the terminal
    public static void Scan(int random, Scanner scanner) {
        System.out.print("Type a guess in: ");
        try {
            int input = scanner.nextInt();
            if (input < random) {
                System.out.println("Bigger");
                Scan(random, scanner);
            } else if (input > random) {
                System.out.println("Smaller");
                Scan(random, scanner);
            } else if (input == random) {
                System.out.print("Correct!\nYou Win!");
            }
        } catch (Exception e) {
            System.out.print("Please input a whole number from 0-1000: ");
            Scan(random, scanner);
        }
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int number = (int)(Math.random() * 1000);

        System.out.println("A random number from 0-1000 has been generated.\nEnter a guess within the range and the program will say if it's bigger or smaller.");
        Scan(number, scanner);
    }

CodePudding user response:

This is one of the usual Scanner problems.

If you call nextInt() and the input data is something that is not an integer, then the erroneous data has not been consumed.

So your next call to nextInt() will try and fail to read the same input.

Use a call to nextLine() in your exception handler to clear it. Scanner.nextLine() returns the rest of the current line - which is the line containing the erroneous not-an-integer data. You don't need to use or keep the result, you just want to consume it.

Any particular reason why this is written as a recursive procedure? A loop would do just as well

  • Related