简体   繁体   中英

read in double from java jtextfield

Seems like a very simple question however I can't read in a double from a jtextfield. I can easily read in a string using getText(); but no luck with double.

My objective is read in the double carry out a subtraction on it and then redisplay it back to the user once the submit buttons pressed...Action listener is working fine and to make it look more simple I didn't add it in...if it helps I can add it.

if (e.getSource() == submit)
            {
                cashRecieved = CashNeeded.getText();

            }

cashRecieved is type double therefore eclipse is complaining understandable stating it can't store a string to a double....

You need to convert the String into a double. To do this, use the parseDouble method:

cashRecieved = Double.parseDouble(CashNeeded.getText());

This returns type double (primitive), whereas valueOf returns type of the class Double.

EDIT:

As Ingo mentioned, you should make sure you take care of the NumberFormatExceptions that occur when you try to parse an invalid string (eg: "Hello123") into a number.

try {
    cashRecieved = Double.parseDouble(CashNeeded.getText());
} catch (NumberFormatException e) {
    e.printStackTrace();
    // handle the error
}
double d = Double.valueOf(CashNeeded.getText());

您不应该大写变量名(我假设CashNeeded是一个)。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM