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

问题描述:

我使用JOptionPane构建了一个小随机数生成器。我所写的例外情况会阻止用户在单击X按钮时退出程序。我做了大量的研究并尝试了几件事,但似乎没有任何工作。Java异常阻止关闭程序(点击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; 
} 
+0

辉煌!作品,非常感谢:D – Dan

+0

不客气。好好学习:) – davidxxx