最初我試圖將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
}
}
請重新表達你的第二句話,並給我們你的例外的完整堆棧跟蹤。 – 2013-02-26 21:28:44
看起來像你需要重構你的代碼,並引入一個方法(拋出異常)來輸入用戶的數據 – 2013-02-26 21:30:34
當你在catch塊中放入與try塊相同的代碼時,是一個很好的標誌,你的邏輯錯了。 – 2013-02-26 21:30:42