0

I wrote a java code, using a few method who use Scanner. the first Method worked well, but the second got stack with the error

"java.util.NoSuchElementException".

The code of the first method maxPile:

 public static int maxPile() {
    Scanner scan = new Scanner(System.in);
    System.out.println("enter max number of piles");
    int pMax = scan.nextInt();
    scan.close();
    return pMax;
}

the code of the second method maxMatches :

public static int maxMatches() {
    Scanner scan = new Scanner(System.in);
    System.out.println("enter max number of matches per pile");
    int mMax = scan.nextInt();
    scan.close();
    return mMax;
}

The methods are identical, but the first worked, the second not... my output -

enter max number of piles
8
enter max number of matches per pile
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 autoNim.autoNim.maxMatches(autoNim.java:89)
at autoNim.autoNim.main(autoNim.java:12)

(the '8' is my input, line 12 call the method MaxMatches, line 89 is xint mMax=scan.nextInt(); from the method)

Rmahajan
  • 1,311
  • 1
  • 14
  • 23
Elad
  • 9
  • 3

1 Answers1

2

Explanation

It is because you closed the scanner. Closing a scanner always closes the underlying resource, i.e. System.in. You can not use System.in anymore after you closed it.

Do not close scanners tied to System.in.

Resources should only be closed by the one who opened them. The JVM opened System.in and it will also close it again when your program finishes. You are not responsible for managing System.in, keep it open.


Exception-safe closing

Note that if you want to close a scanner, you must make sure that it is exception-safe. I.e. you need to wrap it with try-catch-finally. If possible, prefer to use try-with-resources:

try (Scanner scanner = new Scanner(...)) {
    ...
}

Which will auto-close it in an exception-safe manner after the try-block.

Zabuzard
  • 25,064
  • 8
  • 58
  • 82
  • 1
    However it's not recommended to use multiple **Scanner** instances tied with **System.in** There are side effects in defining multiple scanners in your program. You can find detailed explanation on below link: (https://wiki.sei.cmu.edu/confluence/display/java/FIO06-J.+Do+not+create+multiple+buffered+wrappers+on+a+single+byte+or+character+stream) – Jainik Feb 02 '19 at 22:47