问题
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 is the code:
Circle(double x, double y, String color, double radius) {
super(x, y, color); // constructor from class shape which is extended by circle
Scanner r = new Scanner(System.in);
while (radius <= 0)
{
System.out.println("radius has to be > 0.....Give radius again");
if (r.hasNextDouble())
{
radius = r.nextDouble();
}
else
{
r.nextLine(); //25th line
}
}
this.radius = radius;
r.close();
}
If I put as a radius 0 I don't get the chance to make an input and it gives me this message:
radius has to be > 0.....Give radius again
Exception in thread "main" java.util.NoSuchElementException:No line found
at java.util.Scanner.nextLine(Unknown Source)
at pack.Circle.<init>(Circle.java:25)
at pack.Main.main(Main.java:11)
What's wrong?
回答1:
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.
来源:https://stackoverflow.com/questions/30514201/java-util-scanner-throwforunknown-source-error-cant-type-input