如何在此程序中递归调用扫描器?

时间:2018-10-03 21:15:58

标签: java recursion java.util.scanner

这是我的第一篇文章,所以我不确定格式,也没有完整的程序(如果需要,我可以提供)

我正在编写一个程序,该程序要在其中使用扫描程序的方法中,其工作是接收数字,检查其有效性,如果无效,请递归并接收新的数字。

当我运行此程序时,扫描仪将打开,获取数字,然后显示错误信息:

  

线程“主”中的异常java.util.NoSuchElementException           在java.util.Scanner.throwFor(Scanner.java:862)           在java.util.Scanner.next(Scanner.java:1485)           在java.util.Scanner.nextInt(Scanner.java:2117)           在java.util.Scanner.nextInt(Scanner.java:2076)           在Password.getGuess(Password.java:26)           在Password.checkPassword(Password.java:46)           在Password.getGuess(Password.java:35)           在Password.checkPassword(Password.java:46)           在Password.main(Password.java:7)

public static int getRange(){
    int range = (int) Math.pow(10, difficulty);
    return range;
}
public static int getGuess() {
    Scanner in = new Scanner(System.in);
    System.out.println("ENTER PASSWORD_");
    int guess = in.nextInt();
    in.close();
    if (guess > (getRange() - 1) || guess < (getRange() / 10 )) {
        System.out.println("ERROR: INVALID_PASSWORD");
        return getGuess();
    } else {
        checkPassword();
        return guess;
    }
}

1 个答案:

答案 0 :(得分:0)

尝试这样的事情:

boolean validInput = false;

while(!validInput)
{
    System.out.println("ENTER PASSWORD_");

    int guess = in.nextInt();

    if (guess > (getRange() - 1) || guess < (getRange() / 10 ))
    {
        System.out.println("ERROR: INVALID_PASSWORD");
    }
    else
    {
        // this will cause your input loop to terminate
        validInput = true;
    }
}

checkPassword();