java util scanner throwforunknown source error (cant type input)

前端 未结 1 1502
春和景丽
春和景丽 2021-01-27 15:07

I have a problem with a scanner and I don\'t really know what\'s wrong. I have a Circle class and I want to make check loop for its radius on the constructor. Here

相关标签:
1条回答
  • 2021-01-27 15:32

    Scanner.nextLine() throws the NoSuchElementException if it couldn't read a line from the provided InputStream. Since you're using System.in as your input stream and since it will block the thread until it could read the requested line, there is only one reason left, which can cause such a problem: the stream is already closed.

    You're calling Scanner.close() in your Circle constructor, which will not only close the scanner, it will also close the used input stream. That means, the input stream, referenced by the variable System.in is closed, and can't be opened again. So if you already created a circle, or closed the stream somewhere else in your code you will get the mentioned exception.

    To fix the problem, just remove every close call for every reader, like Scanner or BufferedReader, which uses System.in as its source stream.

    And then you should think about extracting the r variable into a dedicated class. Then you can create the Scanner once and use it everywhere where you want to request user input. You can close that scanner if you like to close the application and perform a cleanup.

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