我使用try-catch異常處理寫這個程序:嵌套循環不會工作的Java程序
Scanner keyboard = new Scanner(System.in);
String[] employees = new String[5];
boolean done1 = false;
//input and error exception for entering employee names into an array
for (int i = 0; i < 5; i++)
{//begin for
while (!done1)
{//begin while
System.out.println("Please enter employee's name: ");
try
{//begin try
employees[i] = keyboard.nextLine();
if (employees[i].length() == 0)
throw new Exception("No name was entered.");
if (employees[i].length() >= 31)
throw new Exception("Name entered contains too many "
+ "characters");
for (int check = 0; check < employees[i].length(); check++)
{//begin for
if(Character.isDigit(employees[i].charAt(check)))
throw new Exception("Input contains invalid "
+ "charaters.");
}//end for
done1 = true;
}//end try
catch (Exception a)
{//begin catch
System.out.println("Error: " + a.getMessage());
}//end catch
}//end while
}//end for
當我運行程序時,它踢出來的for循環,只有輸入一審我和其餘的都是空的。我如何讓程序停留在這個循環中並讓它保持錯誤檢查?
你根本不應該爲這類事情使用例外。 – 2011-03-18 22:58:26
@Martin爲什麼不呢?我可以看到這是將錯誤處理與算法分開的簡單方法。對於我們所知道的,後來他可能想要做日誌記錄或其他事情,這可能是許多代碼行。 – 2011-03-18 23:01:41
如果必須的話,您可以輕鬆調用situe中的日誌記錄方法 - 但是我們是否真的記錄了我們丟棄的無效數據?例外情況出現在特殊情況下。 – 2011-03-28 12:27:10