Reputation: 279
While using scanner like following:
Scanner s = new Scanner(System.in);
String response = s.next();
Boolean approved = (response.contains("Y") || response.contains("y")) ? true : false;
if (approved){
Do Stuff
}
s.close();
I'm getting no such Element exception exception:
Exception in thread "main" java.util.NoSuchElementException at java.util.Scanner.throwFor(Unknown Source) at java.util.Scanner.next(Unknown Source)****
I'm calling s (Scanner) multiple times, the runtime error occur on the second call. This is due to closing the scanner and than probably using it again. My question is, I'm creating a new instance of Scanner every time I'm using it so why I'm getting the runTime error?
Upvotes: 3
Views: 5004
Reputation: 92
I think because you are not deleting the scanner. Try to delete the instance of s before calling it again. And if memory isn't a constraint you could always make a new scanner object, but it's better coding practice to properly de-allocate memory when you are done.
Upvotes: -1
Reputation: 2208
The problem is
When a Scanner is closed, it will close its input source if the source implements the Closeable interface.
http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html
Thus scan.close() closes System.in.
To fix it you can make
Scanner scan static or pass every time scanner object in method and close it at last.
Upvotes: 7