Java异常阻止关闭程序(单击X按钮时)

时间:2017-01-23 20:01:03

标签: java exception try-catch joptionpane throw

我使用JOptionPane构建了一个随机数生成器。我写的例外情况会阻止用户在单击X按钮时退出程序。我做了很多研究并尝试过几件事,但似乎没什么用。

这是我的代码:

import javax.swing.JOptionPane;
import java.util.Random;

public class Generate {
    private int number;
    private int min;
    private int max;
    private int repeat;
    Random no = new Random();
    int x = 1;

    void generateNumber() {
        do {
            try {
                String from = (String) JOptionPane.showInputDialog(null, "Welcome to Random Number Generator!\n\nPlease insert your number range.\n\nFrom:", "Random Number Generator", JOptionPane.QUESTION_MESSAGE, null, null, "Enter Number");
                min = Integer.parseInt(from);

                String to = (String) JOptionPane.showInputDialog(null, "To:", "Random Number Generator", JOptionPane.QUESTION_MESSAGE, null, null, "Enter Number");
                max = Integer.parseInt(to);
                System.out.println();

                String count = (String) JOptionPane.showInputDialog(null, "How many numbers would you like?", "Random Number Generator", JOptionPane.QUESTION_MESSAGE, null, null, "Enter Number");
                repeat = Integer.parseInt(count);
                System.out.println();

                for (int counter = 1; counter <= repeat; counter++) {
                    number = no.nextInt(max - min + 1) + min;
                    JOptionPane.showMessageDialog(null, "Random number #" + counter + ": " + number, "Random Number Generator", JOptionPane.PLAIN_MESSAGE);
                }
               x = 2;
            } catch (NumberFormatException e) {
                  JOptionPane.showMessageDialog(null, "INPUT ERROR: please insert a number", "Random Number Generator", JOptionPane.ERROR_MESSAGE);
            } catch (Exception e) {
                  JOptionPane.showMessageDialog(null, "INPUT ERROR: the second number needs to be higher than the first", "Random Number Generator", JOptionPane.ERROR_MESSAGE);
                }
            } while(x == 1);
        }
}

主要:

  class RandomNumber {
    public static void main(String[] args) {
        Generate obj = new Generate();
        obj.generateNumber();
    }
}

This is what happens when I try to close the program

1 个答案:

答案 0 :(得分:0)

from调用后,您不会测试showInputDialog()值。

例如:

String from = (String) JOptionPane.showInputDialog(null,...

此次通话后,您可以直接链接

min = Integer.parseInt(from);
无论from的价值如何 如果fromnull,则您在此catch中完成,因为null不是数字:

  catch (NumberFormatException e) {
        JOptionPane.showMessageDialog(null, "INPUT ERROR: please insert a number", "Random Number Generator",
        JOptionPane.ERROR_MESSAGE);
    }

x仍然以1为值。所以循环条件仍为true

要解决您的问题,您只需测试showMessageDialog()返回的值,如果值为null,则让用户退出该方法。

每次检索用户输入时都要添加此代码,并且要让用户退出:

if (from == null) {
    return;
}
相关问题