0

I have multiple java classes in my project and in each class I am using Scanner class to take input and then I close it in finally clause.

When I use scanner object in main class under do...while loop and call those classes it works fine for one iteration however it gives an Exception as "NO SUCH ELEMENT EXCEPTION".

I removed the scanner close function in all other classes and it works fine.

Why is that so?

Jiri Tousek
  • 12,211
  • 5
  • 29
  • 43
Harshit Singhvi
  • 104
  • 1
  • 7
  • 1
    Closing scanner closes also (or should I said mainly) resource which was read. So if you have scanner reading from `System.in` then when you close scanner this stream will also be closed (and you can't reopen it). This is why you shouldn't create many instances of Scanner which will be handling `System.in` (nor any streams which you don't want to close until end of application). Instead create one and reuse it in other places (maybe pass it as argument of methods which need it). – Pshemo Apr 10 '16 at 13:54
  • Can you share the code? – Darshan Mehta Apr 10 '16 at 13:58
  • Got the solution thanks@Pshemo – Harshit Singhvi Apr 10 '16 at 14:51

0 Answers0