views:

210

answers:

1

So I am working on a program for school, and part of the assignment is to have a bunch of prompts for input pop up. I am using the JOptionPane, which inherently has an OK button and a Cancel button. Now, to make the program exit when they press cancel when the prompt is asking for a string, I have something like this:

firstName = JOptionPane.showInputDialog("Please enter your first name:");
if(firstName == null)System.exit(0);

But I also have to do the same thing for numbers I get as input, both Doubles and Ints. If I try the same thing, it throws an error saying The operator == is undefined for the argument type(s) double, null. So, what is the best way for me to check if they click Cancel when being prompted for a numerical value? Thanks for your help!

Edit #1

Here is the code for the JOptionPane getting a numerical value:

startDateMonth = Integer.parseInt(JOptionPane.showInputDialog("Please enter the start         date month (1-12):"));
+1  A: 

Hi Steve,

JOptionPane.showInputDialog() returns always a string which is the user input. If the user has clicked the Cancel button it will return null. If you want to convert the user input to another type just parse the string. I mean the code you have pasted should remain the same. If you are asking for a different thing, please clarify.

Petar

Petar Minchev
Hey thanks very much for your answer, after re-reading my question I realized it is a little ambiguous. I added the code for my integer JOptionPane, I'm just wondering what I need to do to cancel. If the startDateMonth == what? then cancel. Thanks
Steve
String startDateMonth = JOptionPane.showInputDialog("Please enter the start date month (1-12):");if (startDateMonth == null) System.exit(0);int parsed = Integer.parseInt(startDateMonth);I mean first check if the user has clicked Cancel and then parse the input. Hope it is clear.
Petar Minchev
Ah, and by the way with your previous snippet code Integer.parseInt(JOptionPane.showInputDialog("Please enter the start date month (1-12):")); you will always get a null pointer when the user has clicked cancel. Because you will essentially call Integer.parseInt(null).
Petar Minchev
Success!! Thank you very much!!
Steve
You are welcome:)
Petar Minchev