How to read in dual language in Java?

I am trying to get decimal keyboard input and it just doesn't work. I tried first

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

and that obviously doesn't work very well.

I'm used to just parse ints when they enter the keyboard directly into a variable, but I don't know what I have to do for decimals! I need to be able to use a decimal character like .9 directly from the keyboard and be able to have it in a variable that I can execute with.

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

+4
source share
4 answers
 double d = new Double(JOptionPane.showInputDialog("Please enter a number between 0 and 1:")); 
+4
source

I would use the Double class, not the Integer class

 double d = Double.parseDouble((String)JOptionPane.showInputDialog("Please enter a number between 0 and 1:")); 
+8
source

Have you tried replacing Double with 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)

+3
source

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

+3
source

Source: https://habr.com/ru/post/1300927/


All Articles