views:

162

answers:

4

I am trying to get a decimal input from the keyboard, and it is just not working. First I tried

double d = Integer.parseInt(JOptionPane.showInputDialog(
                                    "Please enter a number between 0 and 1:"));

and that obviously didn't work very well.

I am used to just parsing int's as they come in from the keyboard right into a variable, but I don't know what I am supposed to do for decimals! I need to be able to take a decimal like .9 straight from the keyboard and be able to have it in a variable I can do calculations with.

I know this is a basic question, but I need some help. Thanks!

+3  A: 
double d = new Double(JOptionPane.showInputDialog("Please enter a number between 0 and 1:"));
Avindra Goolcharan
This will work, but it's not the most correct way to do it.
Michael Myers
What is then? Double.parseDouble? Why is that any better?
Avindra Goolcharan
`double d = new Double` creates a object of type `Double` and then immediately discards it in favor of the primitive `double`. `Double.parseDouble` avoids the two unnecessary steps in between.
Michael Myers
+5  A: 

I would use the Double class rather than the Integer class :)

double d = Double.parseDouble(JOptionPane.showInputDialog("Please enter a number between 0 and 1:"));
John Weldon
+3  A: 

Have you tried substituting Double for Integer ?

So Double.parseDouble(JOptionPane.showInputDialog("Please enter a double:")); http://java.sun.com/javase/6/docs/api/java/lang/Double.html#parseDouble(java.lang.String)

Or Double.valueOf(JOptionPane.showInputDialog("Please enter a double:")) http://java.sun.com/javase/6/docs/api/java/lang/Double.html#valueOf(java.lang.String)

Tim
+3  A: 

You should use Double.parseDouble(String). Another option is Double.valueOf(String) and I prefer the later because it's more change tolerant (if the parameter is changed for something else than a String, you may not have to modify your code), even if it creates an unnecessary Double that you don't need in your example.

Pascal Thivent