我有下面的代碼,它能夠完成就好了工作,但你可以看到它是非常冗長,可能會造成混淆:如何最大限度地減少輸入例外
private void addRecord() {
String firstName = JOptionPane.showInputDialog("First Name: ");
if (firstName.length() <= 0){
JOptionPane.showMessageDialog(null, "That is not a valid input.","Input error",JOptionPane.ERROR_MESSAGE);
addRecord();
}//end if
String lastName = JOptionPane.showInputDialog("Last Name: ");
if (lastName.length() <= 0){
JOptionPane.showMessageDialog(null, "That is not a valid input.","Input error",JOptionPane.ERROR_MESSAGE);
addRecord();
}//end if
String a = JOptionPane.showInputDialog("Student Number: ");
int studentNumber = Integer.parseInt(a);
if (a.length() <= 0 || studentNumber == 0){
JOptionPane.showMessageDialog(null, "That is not a valid input.","Input error",JOptionPane.ERROR_MESSAGE);
sortMenu();
}//end if
String major = JOptionPane.showInputDialog("Major: ");
if (major.length() <= 0){
JOptionPane.showMessageDialog(null, "That is not a valid input.","Input error",JOptionPane.ERROR_MESSAGE);
addRecord();
}//end if
String b = JOptionPane.showInputDialog("GPA: ");
double gpa = Double.parseDouble(b);
if (b.length() <= 0 || gpa > 4.0){
JOptionPane.showMessageDialog(null, "That is not a valid input.","Input error",JOptionPane.ERROR_MESSAGE);
sortMenu();
}//end if
tree.addNode(studentNumber, firstName, lastName, major, gpa);
}//end addRecord
有沒有更好的辦法,我可以寫這個來檢查每個輸入,而不必每個輸入都有if語句?我想盡可能地減少這種情況。
考慮到所有if語句不同,我沒有親自看到一種方式,如果它們很常見,可以擴展並重寫JOptionPane方法。 編輯*我也只是注意到,如果在輸入時發生任何錯誤,你完全重新啓動過程,作爲一個用戶,這會讓我非常煩惱 – EyeOfTheHawks
嗯gotcha ..有沒有一種方法,我可以在同一個對話框中包括所有這些提示?而不必爲每個提示顯示一個框 – Luminusss
您可以創建自己的包含4個字段和動作監聽器的框 – EyeOfTheHawks