如何使用JOptionPane退出while循环

时间:2017-10-31 00:16:44

标签: java

我的代码出现问题,如果用户点击CANCEL.OPTIONCLOSED.OPTION,我会尝试退出此循环。我处理了异常,但似乎无法使用窗口上的按钮。该计划从他们的年龄输入中获得用户的生育年份。我遇到的问题是我无法通过按钮结束循环。提前谢谢!

public Integer getBirthYear() {
    boolean prompt = true;
    while(prompt) {
        String enteredAge = showInputDialog(null,"Enter age:");
        try {
            age = Integer.parseInt(enteredAge);
            if(age == JOptionPane.CANCEL_OPTION || age == JOptionPane.CLOSED_OPTION) {
                System.out.println("MADE IT INTO IF");
            }
            age = year - age;
            prompt = false;
            showMessageDialog(null,age);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
    }
    return age;
}

3 个答案:

答案 0 :(得分:0)

showInputDialog有几个重载版本,带有不同的参数。只有最后一个版本的javadoc正确记录了当用户按下取消时返回值为空。

public int getBirthYear() {
    boolean prompt = true;
    while (prompt) {
        String enteredAge = showInputDialog(null,"Enter age:");
        if (enteredAge == null) { // Cancel pressed
            age = -1;
            prompt = false;
        } else {
            try {
                age = Integer.parseInt(enteredAge);
                age = year - age;
                prompt = false;
                showMessageDialog(null, age);
            } catch (NumberFormatException e) {
                showMessageDialog(null, "Enter a valid number");
            }
        }
    }
    return age;
}

可能你想稍微改编一下程序;使年龄成为局部变量或其他。使用int表示实数。 Integer是int的Object包装类。

答案 1 :(得分:0)

对你的问题最简单的答案是,只需在你的try和catch子句之外加上promp = false就可以了:

public Integer getBirthYear() {
boolean prompt = true;
while(prompt) {
    String enteredAge = showInputDialog(null,"Enter age:");
    try {
        age = Integer.parseInt(enteredAge);
        if(age == JOptionPane.CANCEL_OPTION || age == JOptionPane.CLOSED_OPTION) {
            System.out.println("MADE IT INTO IF");
        }
        age = year - age;
        showMessageDialog(null,age);
    } catch (NumberFormatException e) {
        e.printStackTrace();
    }
        prompt = false;
}
return age;
}

答案 2 :(得分:0)

问题在于范围。进入的年龄并没有进入捕获区。我解决了这个问题。

    public Integer getBirthYear() {
    boolean prompt = true;
    do {
        try {
            age = year - Integer.parseInt(showInputDialog(null,"Enter age:"));
            prompt = false;
            showMessageDialog(null, age);
        } catch (NumberFormatException e) {
            String ageEntered = showInputDialog(null,"Enter age:");
            e.printStackTrace();
            if(ageEntered == null) { //close the file if Cancel is chosen
                prompt = false;
            }
        }
    } while(prompt);
    return age;
}