java.util.NoSuchElementException 关闭扫描仪时出错

java.util.NoSuchElementException Error when closing the Scanner

public class a2 {

    public static int read() {
        Scanner sc = new Scanner(System.in);
        int num = sc.nextInt();
        sc.close();
        return num;
    }

    public static void out (int a, int b) {
        System.out.println("Sum: " + (a+b));
        System.out.println("Difference: " + (a-b));
        System.out.println("Product: " + (a*b));
        System.out.println("Quotient: " + ((double)a/(double)b));
        System.out.println("Remainder: " + (a%b));
    }

    public static void main(String[] args) {
        System.out.println("Please enter two integers!:");
        int a = read();
        int b = read();     
        out(a,b);
    } 
} 

我的代码确实有点理解问题。每次我 运行 代码时,我都会在输入第一个整​​数后收到此错误消息。

Exception in thread "main" java.util.NoSuchElementException at java.util.Scanner.throwFor(Unknown Source) at java.util.Scanner.next(Unknown Source) at java.util.Scanner.nextInt(Unknown Source) at java.util.Scanner.nextInt(Unknown Source) at a2.read(a2.java:6) at a2.main(a2.java:22)

我发现,当我删除 "sc.close();" 行或当我将两个变量之一定义为常量时,它工作得很好。有人可以给我解释一下吗?

您使用 sc.Close 关闭了 System.in,这将在它再次尝试读取时抛出错误。

你不能这样做:

int a = read();
int b = read();     

因为读取方法正在关闭扫描器并在后台关闭来自系统的输入流...

全局声明扫描器对象并读取所需的内容,最后关闭它

示例:

private static Scanner sc;

public static int read() {

    return sc.nextInt();
}

public static void out(final int a, final int b) {
    System.out.println("Sum: " + (a + b));
    System.out.println("Difference: " + (a - b));
    System.out.println("Product: " + a * b);
    System.out.println("Quotient: " + (double) a / (double) b);
    System.out.println("Remainder: " + a % b);
}

public static void main(final String[] args) {
    System.out.println("Please enter two integers!:");
    sc = new Scanner(System.in);
    int a = read();
    int b = read();
    sc.close();
    out(a, b);
}

问题是您正在关闭 System.in(Scanner.close() 关闭基础流)。一旦你这样做,它就会保持关闭状态,并且无法输入。您通常不想使用标准输入来执行此操作。