Reputation: 1212
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....
Upvotes: 0
Views: 19121
Reputation: 5840
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
}
Upvotes: 4
Reputation: 3822
double d = Double.valueOf(CashNeeded.getText());
You shouldn't capitalize variable names (I assume CashNeeded is one).
Upvotes: 1