java.util.NoSuchElementException关闭扫描程序时出错

时间:2017-03-21 11:26:27

标签: java java.util.scanner nosuchelementexception

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

我对我的代码有一些了解。每次运行代码时,输​​入第一个整​​数后都会收到此错误消息。

  

线程“main”中的异常java.util.NoSuchElementException at   java.util.Scanner.throwFor(未知来源)at   java.util.Scanner.next(未知来源)at   java.util.Scanner.nextInt(未知来源)at   java.util.Scanner.nextInt(未知来源)at a2.read(a2.java:6)at   a2.main(a2.java:22)

当我删除“sc.close();”时,我想通了当我将两个变量中的一个定义为常量时,它可以完美地运行。有人可以向我解释一下吗?

3 个答案:

答案 0 :(得分:3)

你不能这样做:

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

答案 1 :(得分:3)

问题是你正在关闭System.in(Scanner.close()关闭底层流)。一旦这样做,它就会保持关闭状态,并且无法输入。您通常不希望使用标准输入。

答案 2 :(得分:2)

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