2014-04-14 82 views
0

我有下面的代碼,它能夠完成就好了工作,但你可以看到它是非常冗長,可能會造成混淆:如何最大限度地減少輸入例外

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語句?我想盡可能地減少這種情況。

+0

考慮到所有if語句不同,我沒有親自看到一種方式,如果它們很常見,可以擴展並重寫JOptionPane方法。 編輯*我也只是注意到,如果在輸入時發生任何錯誤,你完全重新啓動過程,作爲一個用戶,這會讓我非常煩惱 – EyeOfTheHawks

+0

嗯gotcha ..有沒有一種方法,我可以在同一個對話框中包括所有這些提示?而不必爲每個提示顯示一個框 – Luminusss

+0

您可以創建自己的包含4個字段和動作監聽器的框 – EyeOfTheHawks

回答

1

試試這個:

private void checkString(String st, boolean or) { 
    if (st.length() <= 0 || or){ 
     JOptionPane.showMessageDialog(null, "That is not a valid input.","Input error",JOptionPane.ERROR_MESSAGE); 
     addRecord(); 
    } 
} 
private void addRecord() { 
    String firstName = JOptionPane.showInputDialog("First Name: "); 
    checkString(firstName, false); 

    String lastName = JOptionPane.showInputDialog("Last Name: "); 
    checkString(lastName, false); 

    String a = JOptionPane.showInputDialog("Student Number: "); 
    int studentNumber = Integer.parseInt(a); 
    checkString(a, studentNumber == 0); 

    String major = JOptionPane.showInputDialog("Major: "); 
    checkString(major, false); 

    String b = JOptionPane.showInputDialog("GPA: "); 
    double gpa = Double.parseDouble(b); 
    checkString(b, gpa > 4.0); 

    tree.addNode(studentNumber, firstName, lastName, major, gpa); 
} 

or參數包含的額外條件。

+0

是的,我想這個減少了一點,謝謝! – Luminusss

+0

東西看起來不像。如果第一個名字沒問題,但姓氏不是,你不打算再次詢問第一個名字嗎?如果你有錯誤,堆棧可能變得非常大。 – JustinKSU

+0

@JustinKSU在問題部分看到我的評論,我意識到,無論什麼輸入都是錯誤的,它仍然會回到最初。它還沒有完成,這當然是會改變的。感謝壽:) – Luminusss

相關問題