java - 如何最大限度地减少输入异常

标签 java exception

我有以下代码,它可以很好地完成工作,但正如您所看到的,它非常冗长并且可能令人困惑:

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 语句?我想尽可能地减少这种情况。

最佳答案

试试这个:

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 参数用于额外条件。

关于java - 如何最大限度地减少输入异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23066421/

相关文章:

java - 从 httppost 响应中解析 xml

java - Spring OAuth2 刷新 token

java - 带比较器的有序流

scala - 在 Scala 中结合 Futures (Twitter) 和两者

python - 如何获取异常列表?

java - 如何配置单线程ForkJoinPool?

java - 将字节转换为 long : Why do some implementations bitwise-AND each byte with 0xff?

Java - 捕获异步方法的异常

exception - iOS UIWebView DOM异常18如何排查?

C++ - 返回码异常的参数