简体   繁体   English

重复异常

[英]Repeating an Exception

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. 我希望能够重复这个问题,直到他们输入正确的值,该值是double或int值。 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. 您的第二个parseDouble不在try / catch中,因此不会被捕获。 Also, your while(false) will only let this execute the first time. 同样,您的while(false)将只让它第一次执行。 Does this work for you? 这对您有用吗? Also, you could do a while(true) and break after the parseDouble. 另外,您可以执行一会儿(true)并在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 首先,您需要更改while循环的条件,并且还需要打破它

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM