Jacques Naudé Jacques Naudé - 21 days ago 5
Java Question

Java - Convert int number

What I want to do :

I made a BMI calculator (Formula=(KG*KG)/M)
The input takes eg 186 but i get an error when inserting 1.86 (For height in metres)

java.lang.NumberFormatException: For input string: "1.86"


Here is my code :

if (txtHeight.getText().length() > 0 && txtWeight.getText().length() > 0){
height = Integer.parseInt(txtHeight.getText());
heightsqr = (int) Math.pow(height, 2);
mass = Integer.parseInt(txtWeight.getText());
bmi = (heightsqr/ mass);
lblBmi.setText("Current BMI : " + Integer.toString(bmi));
}
else{
JOptionPane.showMessageDialog(this, "Please enter your weight in KG and your Height in M");
}


It's a pretty basic error that I just cant seem to fix

Answer

As the stacktrace says, you can't convert 1.86 to int. Why? because it's a double.

try:

mass = Double.parseDouble(txtWeight.getText());

In Java, we have types. int can only store integer. Real numbers can be stored in floats and doubles but remember, that you can lose precision.

I don't know your whole code, so I can't tell you, what is the type of mass. In case you have the following somewhere in your code:

int mass;

change it to:

double mass;

Some random thoughts:
As you have already seen, there is a possibility that the Exception will be thrown. It happens depending on user input I believe. In Java we have a mechanism to secure. It's a try-catch block. It can be used for example in the following way:

try {
    mass = Double.parseDouble("1,86");
} catch (NumberFormatException e) {
    //somehow notify user that he has mistaken and work it out according to your business logic.
}

I strongly recommend reading this tutorial which I have provided on StackOverflow question What is a NumberFormatException and how can I fix it.

Comments