-2

Cant figure out. On the second while-run, it will not even wait for user input and crashes instead with

Exception in thread "main" java.util.NoSuchElementException: No line found

Ofc if theres no input, there hardly is a line I assume. So what may I do here?

 while (go) {

        Scanner jain = new Scanner(System.in);
        String jainstr = jain.nextLine();
        jain.close();
}

Intellij 2018.2

pikkuez
  • 310
  • 1
  • 18
  • 1
    *Ofc if theres no input, there hardly is a line I assume* - True, but the scanner waits for the input. You should try moving the scanner declaration outside the while loop and close it after the loop. – BackSlash Aug 24 '18 at 15:22
  • 2
    Don't close `jain` in the loop. – Andy Turner Aug 24 '18 at 15:22
  • Possible duplicate of [java.util.NoSuchElementException - Scanner reading user input](https://stackoverflow.com/questions/13042008/java-util-nosuchelementexception-scanner-reading-user-input) – Tom Aug 24 '18 at 15:29
  • @BackSlash "and close it after the loop." .. that's a bad advice. – Tom Aug 24 '18 at 15:30
  • @Tom Why? If the program is just that loop, the scanner should be closed right after the loop. More generally, the scanner should be closed before the app terminates, and this applies to _everything_ involving a stream. You may argue that *it wasn't created by you, so you shouldn't be closing it* - Well, that's a matter of choice. If you don't need it anymore it's perfectly fine to close it. – BackSlash Aug 24 '18 at 15:31
  • @BackSlash Yes, "if it only has that" and we don't know that, but to be honest, that's pretty unlikely. – Tom Aug 24 '18 at 15:34
  • @Tom We have to talk about what's shown. In this example, the issue is that the scanner is created and closed inside the loop, while creation and closing should be outside. There may be multiple different scenarios, but the answer to this specific question is that declaration and closing should be moved before and after the loop. – BackSlash Aug 24 '18 at 15:38

1 Answers1

3

jain.close() closes the Scanner, which has the effect of closing the underlying stream, System.in.

When you try to read from that stream again, you will get an error, because you have already closed it.

Don't close the scanner in the loop.

Moreover, don't create a new scanner on each loop. Create a scanner before the loop, and reuse it inside the loop.

You don't really need to close the Scanner. IDEs often complain at you for not closing it, because if the stream is something like a FileInputStream, you do need to close it to avoid a resource leak.

The general rule is that you should only close streams that you open: you didn't open System.in, so don't close it.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243