0

我有一个应该处理异常的 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;
                }
            }
4

1 回答 1

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
    }
}
于 2013-08-23T12:27:28.947 回答