How can I convert a string to a double using parseDouble?

69 views Asked by At
JLabel label1 = new JLabel("Annual Rental Income");
JTextField textf1 = new JTextField("0.1",16);
//converting a string to a double cuz user input needs to be numbers
double a = Double.parseDouble(textf1.getText());
        
JLabel label2 = new JLabel("Purchased Price");
JTextField textf2 = new JTextField("1.2",16);
double b = Double.parseDouble(textf2.getText());

double result = (a / b) * 100;

Hi. I'm trying to run a rental yield program based on a user's input but it only calculate 0.1 and 1.2 in Jtextfield. It didn't calculate what the user add. I added 0.1 and 1.2 cuz I got "NumberFormatException" if I add words.What did I do wrong in my code. Please help.

1

There are 1 answers

0
Sajid Junejo On

you need to parse the text field values at the moment when you want to calculate the result, not when you create the text fields. This way, you'll get the updated values entered by the user.