I am using an exception in my code below. I want to be able to repeat the question until they enter the correct value which is a double or int value. My problem is at when I ask for a value the second time. What should I change or use to fix this?
do{
try{
System.out.println("Enter number");
number = Double.parseDouble(br.readLine());
} catch(Exception ex) {
System.out.println(ex +"\nEnter an int or double value");
number = Double.parseDouble(br.readLine());
}
} while(false);
Output:
Enter number
qwe
java.lang.NumberFormatException: For input string: "qwe"
Enter an int or double value
we
Exception in thread "main" java.lang.NumberFormatException: For input string:
"we"
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1241)
at java.lang.Double.parseDouble(Double.java:540)
at practicedd.PracticeDD.main(PracticeDD.java:38)
Java Result: 1
Your second parseDouble is not in a try/catch, so nothing gets caught. Also, your while(false) will only let this execute the first time. Does this work for you? Also, you could do a while(true) and break after the parseDouble.
Double number = null;
do{
try{
System.out.println("Enter number");
number = Double.parseDouble(br.readLine());
}catch(Exception ex){
System.out.println(ex +"\nEnter an int or double value");
}
}while(number==null);
} }
Your code is almost right. First, you need to change the condition of the while
loop, and also, you need to break out of it
do{
try{
System.out.println("Enter number");
number = Double.parseDouble(br.readLine());
break;
} catch(Exception ex) {
System.out.println(ex +"\nEnter an int or double value");
number = Double.parseDouble(br.readLine());
}
} while(true);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.