价值不会被带来

时间:2014-11-25 16:41:15

标签: java

所以当我为第二个问题输入一个值时,我的程序就停止了,没有任何反应。如果我为第一个问题输入一个值,那么为第二个问题输入一个错误的值,然后尝试取消该程序,它给我的显示方法(除非允许该值,否则它不应该除外)。

我的计划出了什么问题?

    while (invalidInput) {
        //Try...catch block to find any input errors for the number.
        try {
            finalNum = JOptionPane.showInputDialog(null,
                    "Please enter a number between 1 and 20",
                    "The Word Factory", JOptionPane.QUESTION_MESSAGE);

            while (finalNum != null) {
                finalNumber = Integer.parseInt(finalNum);
                if (finalNumber > 20 || finalNumber < 1) {
                    JOptionPane.showMessageDialog(null, "The number you entered was not between 1 and 20."
                                    + " \nPlease try again.",
                            "Input Error", JOptionPane.ERROR_MESSAGE);
                    finalNum = JOptionPane.showInputDialog(null,
                            "Please enter a number between 1 and 20",
                            "The Word Factory", JOptionPane.QUESTION_MESSAGE);

                    Part2 object = new Part2(finalString, finalNumber);
                    object.answer2 = finalString;
                    object.number2 = finalNumber;
                    object.display();
                }
            }
            invalidInput = false;
        } catch (NumberFormatException ex) {
            JOptionPane.showMessageDialog(null, "The number you entered was not between 1 and 20."
                            + " \nPlease try again.",
                    "Input Error", JOptionPane.ERROR_MESSAGE);
        }
    }

1 个答案:

答案 0 :(得分:0)

我试图修复你的一些逻辑。你处于一个无限循环中,因为没有办法摆脱它。我通过制作一个有效数字布尔值来解决这个问题。也为什么外部while循环?这无缘无故地增加了时间复杂性。所以摆脱它并替换为if

if (invalidInput)
            finalNum = JOptionPane.showInputDialog(null,
                     "Please enter a number between 1 and 20",
                    "The Word Factory", JOptionPane.QUESTION_MESSAGE);
             boolean valid = false;
            while (valid == false)
            {
                finalNumber = Integer.parseInt(finalNum);

                if( finalNumber > 20 || finalNumber < 1)
                {
                    JOptionPane.showMessageDialog(null, "The number you entered was not between 1 and 20."
                    + " \nPlease try again.",
                   "Input Error", JOptionPane.ERROR_MESSAGE);

                    finalNum = JOptionPane.showInputDialog(null,
                     "Please enter a number between 1 and 20",
                    "The Word Factory", JOptionPane.QUESTION_MESSAGE);

                    Part2 object = new Part2(finalString, finalNumber);
                    object.answer2 = finalString;
                    object.number2 = finalNumber;
                    object.display();
                }
             else
               valid = true;

            }

        }