Here is my Java code:
Scanner userInput = new Scanner(System.in);
while (true) { // forever loop
try {
System.out.print("Please type a value: "); // asks user for input
double n = userInput.nextDouble(); // gets user input as a double
break; // ends if no error
}
catch (Throwable t) { // on error
System.out.println("NaN"); // not a number
}
}
You can see what this is supposed to do from the comments.
But when I enter in something that’s not a number, this happens:
Please type a value: abc
NaN
Please type a value: NaN
Please type a value: NaN
Please type a value: NaN
Please type a value: NaN
Please type a value: NaN
Please type a value: NaN
and so on until I force stop it.
In Python I would just do this:
while True:
try:
n = float(raw_input("Please type a value: "))
break
except Exception:
print "NaN"
How do I do this in Java?
I’ve tried using a do while.
you should use scanner class inside the while loop then only it will ask next input value if the given input value is wrong.