I'm trying to write a function to validate the user's input. It only returns when the user inputs a double number.
private static double getDouble(String name) {
double res = 0;
Scanner s = new Scanner(System.in);
while (true) {
System.out.println("Please input " + name + ":");
if (s.hasNextDouble()) {
res = s.nextDouble();
break;
}
else s.nextLine();
}
s.close();
return res;
}
However, it only works first time. If I call the function second time right after the first time, the nextLine()
will throw an exception.
double length = 0, width = 0;
length = getDouble("length of picture");
width = getDouble("width of picture");
Please see the
Could someone tell me what the mistake I have made here? And how to fix/avoid it?
Thank you.