【问题标题】:Multiple Try/Catch With Repeating JPaneInput [duplicate]重复 JPaneInput 的多次尝试/捕获 [重复]
【发布时间】:2013-08-26 11:47:48
【问题描述】:

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

【问题讨论】:

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


    【解决方案1】:

    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
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-12-08
      • 1970-01-01
      • 2020-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-16
      相关资源
      最近更新 更多