Recursive function doesn't work with try/catch?

Viewed 130

I'm pretty new to java, and am making a java personality quiz for my course. I am making a function that checks for an answer for an integer between 0-5(inclusive), using the scanner, and if the answer is not valid, then to redo it recursively. I used a try/catch in case there was no int, however when running it and typing in a non-number, it repeats forever. I'm pretty sure this is the recursion not working, but could anyone help me find what is wrong with this code.

public static int checkAnswer(String question, Scanner scan) {
        try {
            int toCheck = scan.nextInt();
            scan.nextLine();
            if(toCheck<=5 && toCheck >=0) {
                return toCheck;
            }else {
                System.out.println("No, write a number from 0-5");
                System.out.println(question);
                return checkAnswer(question, scan);
            }
        } catch(InputMismatchException exception) {
            System.out.println("No, not a line, a number, please");
            System.out.println(question);
            return checkAnswer(question, scan);
        }
    }
1 Answers

When the Scanner throw an InputMismatchException, you should clean the line because it wasn't read correctly. So, you need this:

public static int checkAnswer(String question, Scanner scan) {
    try {
        int toCheck = scan.nextInt();
        scan.nextLine();
        if(toCheck<=5 && toCheck >=0) {
            return toCheck;
        }else {
            System.out.println("No, write a number from 0-5");
            System.out.println(question);
            return checkAnswer(question, scan);
        }
    } catch(InputMismatchException exception) {
        System.out.println("No, not a line, a number, please");
        System.out.println(question);
        scan.nextLine();
        return checkAnswer(question, scan);
    }
}

Look that I've added a scan.nextLine(); on the catch block.

Related