I've built a little random number generator using JOptionPane. The exceptions that I've written prevent the user from quitting the program when clicking the X button. I've done lots of research and tried several things but nothing seems to work.
Here's my code:
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);
}
}
Main:
class RandomNumber {
public static void main(String[] args) {
Generate obj = new Generate();
obj.generateNumber();
}
}
You don't test the from
value after showInputDialog()
invocations.
For example here :
String from = (String) JOptionPane.showInputDialog(null,...
After this call, You chain directly with
min = Integer.parseInt(from);
whatever the value of from
.
If from
is null
you finish in this catch
as null
is not a number :
catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null, "INPUT ERROR: please insert a number", "Random Number Generator",
JOptionPane.ERROR_MESSAGE);
}
And x has still 1
as value. So the loop condition is still true
.
To solve your problem, you just to test the value returned by showMessageDialog()
and if the value is null
, let the user exits from the method.
Add this code at each time you retrieve a user input and that you want to enable the user to exit :
if (from == null) {
return;
}