为什么这里没有发生任何TouchElementException?

ehxuflar  于 2021-08-25  发布在  Java
关注(0)|答案(0)|浏览(186)

当我在下面的代码中输入输入ctrl+d时,它会创建一个NoTouchElementException对象并转到catch块,然后执行getint方法,但在这个方法中,我们创建一个scanner对象并从发生异常的用户处获取输入。此输入不是以前的输入,为什么会出现错误?

public static void main(String[] args) {
    int x;
    try {
        x = getInt();
    } catch(NoSuchElementException e) {
        x=getInt();
    }

}
private static int getInt() {
    Scanner s=new Scanner(System.in);

    System.out.println("Please enter an integer ");
    while(true) {
        try {
            return s.nextInt(); //exception occurs here
        } catch(InputMismatchException e) {
            s.nextLine();
            System.out.println("Please enter a number using only the digits 0 to 9 ");
        }
    }
}

//输出

Please enter an integer 
    ِ^D
Please enter an integer 
Exception in thread "main" java.util.NoSuchElementException
        at java.base/java.util.Scanner.throwFor(Scanner.java:937)
        at java.base/java.util.Scanner.next(Scanner.java:1594)
        at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
        at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
        at Main.getInt(Main.java:22)
        at Main.main(Main.java:12)

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题