![](/img/trans.png)
[英]JAVA: Problems with Exception-Handling? Program only catches Exception once
[英]Exception Handling works only once in running program
最初我試圖將try
語句放入while
循環中,但是,遇到了幾個錯誤。 該程序運行完美,除非我輸入一個不規則字符,一旦它給我輸入我創建的打印行,但是,當我再次輸入另一個時,該行不會彈出,而是給我一個格式異常錯誤。
AddNumbersrealone2.java
import java.io.*;
// create the class
public class AddNumbersrealone2
{
// allows i/o
public static void main (String [] args) throws IOException
{ // initalize variables and strings
BufferedReader myInput = new BufferedReader (new InputStreamReader (System.in));
String sumNumbers;
//String go;
double num ;
double total = 0.0;
// asks user questions and instructions
System.out.println("Hello, the following program will ask for your input of a number ");
System.out.println("Each time you input a number a running total will be added to each previous number") ;
System.out.println("Once ready input a number to start!");
// try and catch block
try {
num = 0;
// while statement if this occurs stop the program, in this case if a negative integer is inputted
while (num >= 0) {
// Contious question asked
System.out.println("Input another number...");
sumNumbers = myInput.readLine();
num = Double.parseDouble (sumNumbers);
// calculates number (Running total)
total = total + num;
System.out.println(total);
// end error trap
}
}
catch (Exception e){
System.out.println("Please refrain from entering regular characters!");
num = 0;
// re- while statement if this occurs stop the program, in this case if a negative integer is inputted
while ( num >= 0) {
// input question after a character is inputted
System.out.println("Please input a number: ");
sumNumbers = myInput.readLine();
num = Double.parseDouble (sumNumbers);
total = total + num;
System.out.println(total);
// ending statement
}
}
System.out.println("You entered a negative number, the program will exit now");
System.out.println("Good-bye!");
// Complete class body
}
}
你想要一些東西來捕捉Double.parseDouble周圍的異常
例如。
while(num >= 0)
{
// input question after a character is inputted
System.out.println("Please input a number: ");
sumNumbers = myInput.readLine();
try{
num = Double.parseDouble (sumNumbers);
total = total + num;
System.out.println(total);
} catch(Exception e)
{
System.out.println("Please enter a proper number");
}
// ending statement
}
您的問題是,只要拋出第一個異常,您的程序就會陷入catch語句內的while()循環中。 因此,如果輸入了另一個無效輸入,則在第二個while循環中處理它,其中沒有try-catch語句。 一個很好的解決方法是讓你的try語句只包含你所說的num = Double.parseDouble(sumNumbers);的行。 捕獲異常時,以continue結束; 聲明,以便您的程序循環回頭,並要求另一個輸入。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.