递归函数不适用于try / catch吗?

时间:2019-10-18 16:42:56

标签: java recursion java.util.scanner

我对Java很陌生,并且正在为我的课程进行Java个性测验。我正在制作一个函数,使用扫描仪检查0-5(含)之间整数的答案,如果答案无效,则以递归方式重做。我使用了try / catch,以防万一没有整数,但是在运行它并输入非数字时,它将永远重复。我很确定这是递归不起作用的,但是谁能帮我找到这段代码有什么问题。

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 个答案:

答案 0 :(得分:2)

Scanner抛出InputMismatchException时,您应该清理该行,因为它无法正确读取。因此,您需要这样做:

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);
    }
}

看起来我在scan.nextLine();块上添加了catch