簡體   English   中英

重復異常

[英]Repeating an Exception

我在下面的代碼中使用異常。 我希望能夠重復這個問題,直到他們輸入正確的值,該值是double或int值。 我的問題是第二次要求輸入值時。 我應該更改或使用什么來解決此問題?

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

輸出:

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

您的第二個parseDouble不在try / catch中,因此不會被捕獲。 同樣,您的while(false)將只讓它第一次執行。 這對您有用嗎? 另外,您可以執行一會兒(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);

}}

您的代碼幾乎是正確的。 首先,您需要更改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