Java新手,所以任何幫助將不勝感激。在JTextField中有一個數據驗證的小問題。 要求用戶輸入他們的年齡,他們是否吸菸,以及他們是否超重。 驗證吸菸和體重的效果很好,我設定的年齡限制也是如此。JTextField數據驗證
但是,如果我在ageField JTextField中輸入一個字母,它似乎會卡住並且不會打印其他驗證錯誤。 (例如,它會正確打印「年齡必須是整數」,但是如果我也在smokesField中鍵入「h」,「煙霧輸入應該是Y,y,N或n」將不會被打印)。
對不起,這是一個漫長而臃腫的解釋!
反正這裏是我遇到,三江源困難代碼:
public void actionPerformed(ActionEvent e)
{
String ageBox = ageField.getText();
int age = 0;
if (e.getSource() == reportButton)
{
if (ageBox.length() != 0)
{
try
{
age = Integer.parseInt(ageBox);
}
catch (NumberFormatException nfe)
{
log.append("\nError reports\n==========\n");
log.append("Age must be an Integer\n");
ageField.requestFocus();
}
}
if (Integer.parseInt(ageBox) < 0 || Integer.parseInt(ageBox) > 116)
{
log.append("\nError reports\n==========\n");
log.append("Age must be in the range of 0-116\n");
ageField.requestFocus();
}
if (!smokesField.getText().equalsIgnoreCase("Y") && !smokesField.getText().equalsIgnoreCase("N"))
{
log.append("\nError reports\n==========\n");
log.append("Smoke input should be Y, y, N or n\n");
smokesField.requestFocus();
}
if (!overweightField.getText().equalsIgnoreCase("Y") && !overweightField.getText().equalsIgnoreCase("N"))
{
log.append("\nError reports\n==========\n");
log.append("Over Weight input should be Y, y, N or n\n");
smokesField.requestFocus();
}
}
第二個'Integer.parseInt(ageBox)'會拋出異常 – Jerry06