I'm working on reading integers into a list in Java, and I found an exception that gets thrown when putting Scanner & nextInt() in the loop.
Exception gets thrown on the Scanner class in this code:
do{
System.out.println("?");
Scanner in = new Scanner(System.in);
input = in.nextInt();
in.close();
if(input != SENTINEL)
numberList.add(input);
}while(input != SENTINEL);
Whereas moving the Scanner initialization and close outside of the loop works just fine:
Scanner in = new Scanner(System.in);
//receive input integers from user
do{
System.out.println("?");
input = in.nextInt();
if(input != SENTINEL)
numberList.add(input);
}while(input != SENTINEL);
in.close();
Why is it that the exception occurs when initializing the Scanner class in the loop? Thanks!
Exception is:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at main.Run.main(Run.java:25)