多次尝试/捕获重复JPaneInput

时间:2013-08-23 12:14:33

标签: java exception exception-handling try-catch joptionpane

我有一个应该处理异常的java gui应用程序。这是我的程序的总体思路:它应该接受整数类型的输入。输入对话框应该导致应该捕获的异常并打印消息“坏号”。 但是,我的问题是,如果用户输入空字符串和/或错误的格式编号,如何重复JPanelInput。此外,如果用户选择了CANCEL选项,请退出JOptionPane。

String strIndex = this.showInputDialog(message, "Remove at index");
int index;

// while strIndex is empty && str is not type integer
while (strIndex.isEmpty()) {
      strIndex = this.showInputDialog(message, "Remove at index");
      try {
            if (strIndex.isEmpty()) {

            }
        } catch (NullPointerException np) {
            this.showErrorMessage("Empty field.");
        }


        try {
            index = Integer.parseInt(strIndex);
        } catch (NumberFormatException ne) {
            this.showErrorMessage("You need to enter a number.");
        }
}


    void showErrorMessage(String errorMessage) {
        JOptionPane.showMessageDialog(null, errorMessage, "Error Message", JOptionPane.ERROR_MESSAGE);
    }

    String showInputDialog(String message, String title) {
        return JOptionPane.showInputDialog(null, message, title, JOptionPane.QUESTION_MESSAGE);
    }

更新:

String strIndex;
            int index;
            boolean isOpen = true;

            while (isOpen) {
                strIndex = view.displayInputDialog(message, "Remove at index");
                if (strIndex != null) {
                    try {
                        index = Integer.parseInt(strIndex);
                        isOpen = false;
                    } catch (NumberFormatException ne) {
                        view.displayErrorMessage("You need to enter a number.");
                    }
                } else {
                    isOpen = false;
                }
            }

1 个答案:

答案 0 :(得分:2)

如果用户选择取消,则

showInputDialog()返回null。所以这是基本算法。我会让你把它翻译成Java:

boolean continue = true
while (continue) {
    show input dialog and store result in inputString variable
    if (inputString != null) { // user didn't choose to cancel
        try {
            int input = parse inputString as int;
            continue = false; // something valid has been entered, so we stop asking
            do something with the input
        }
        catch (invalid number exception) {
            show error
        }
    }
    else { // user chose to cancel
        continue = false; // stop asking
    }
}