Java Scanner no line found, and then Scanner closed error?

前端 未结 3 1890
名媛妹妹
名媛妹妹 2021-01-27 18:00

I have Java code that asks for user input and then stores this data in a string variable. The below function is part of a class called \'number\' and is called in the main funct

相关标签:
3条回答
  • 2021-01-27 18:10

    You have to close the scanner when everything is done.

    0 讨论(0)
  • 2021-01-27 18:13

    Scanner.close() documentation states that

    If this scanner has not yet been closed then if its underlying readable also implements the Closeable interface then the readable's close method will be invoked. If this scanner is already closed then invoking this method will have no effect.

    On closing scanner, you are also closing System.in input stream, so when you reopen the scanner it will not find any open input stream.

    Refer : java.util.NoSuchElementException - Scanner reading user input

    Better pass scanner object from outside method as argument and then close it in calling method only when you are done with it.


    Just to point out, is your String object str Static? If not then you can't use it in your static method. Better you remove the static from method declaration.

    0 讨论(0)
  • 2021-01-27 18:13

    You have closed the scanner inout stream readIn.close(); twice.

    You are closing the stream before picking line by line from the file. So you have to close it once after all the instances that use readIn is finished.

    0 讨论(0)
提交回复
热议问题