java.util.NoSuchElementException Error when closing the Scanner

不想你离开。 提交于 2019-12-11 10:15:09

问题


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

I do have a little understanding problem with my code. Everytime I run the code, I get this Error Message after I enter the first integer.

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)

I figured out, when I delete the "sc.close();" line or when I define one of the two variables as a constant it works perfectly fine. Could someone explain this to me?


回答1:


You just can not do this:

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

because read method is closing the scanner and behind the scenes closing the input stream from the System in too...

declare scanner object globally and read as much you need and finally close it

Example:

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



回答2:


The problem is you are closing System.in (Scanner.close() closes the underlying stream). Once you do that, it stays closed, and is unavailable for input. You don't normally want to do that with standard input.




回答3:


You close System.in with sc.Close which will throw an error when it tries to read again.



来源:https://stackoverflow.com/questions/42925771/java-util-nosuchelementexception-error-when-closing-the-scanner

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!