gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 11:51:10 25 4
gpt4 key购买 nike

我使用 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

最佳答案

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

例如这里:

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

关于Java 异常阻止关闭程序(单击 X 按钮时),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41814590/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com