java.util.NoSuchElementException Error when closin

2019-07-31 10:54发布

问题:

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.