Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Division in Java always results in zero (0)? [duplicate]

The function below gets two values from sharedpreferences, weight and height, and I use these to calculate the BMI, When I print the content of the values I get the values i have entered in the sharedprefs ( which is good) but then when i run a division operation on them, I always get 0 as a result.. Where is the error?

public int computeBMI(){
    SharedPreferences customSharedPreference = getSharedPreferences(
            "myCustomSharedPrefs", Activity.MODE_PRIVATE);

    String Height = customSharedPreference.getString("heightpref", "");
    String Weight = customSharedPreference.getString("weightpref", "");

    int weight = Integer.parseInt(Weight);
    int height = Integer.parseInt(Height);
    Toast.makeText(CalculationsActivity.this, Height+" "+ Weight , Toast.LENGTH_LONG).show();

    int bmi = weight/(height*height);
    return bmi;

}
like image 389
callback Avatar asked May 04 '12 20:05

callback


People also ask

Does Java allow division by zero?

To sum things up, in this article we saw how division by zero works in Java. Values like INFINITY and NaN are available for floating-point numbers but not for integers. As a result, dividing an integer by zero will result in an exception. However, for a float or double, Java allows the operation.

Can a division result in zero?

These notes discuss why we cannot divide by 0. The short answer is that 0 has no multiplicative inverse, and any attempt to define a real number as the multiplicative inverse of 0 would result in the contradiction 0 = 1.

How does division work in Java?

Java does integer division, which basically is the same as regular real division, but you throw away the remainder (or fraction). Thus, 7 / 3 is 2 with a remainder of 1. Throw away the remainder, and the result is 2. Integer division can come in very handy.

What happens when the value of a variable is divided by zero in Java?

Division by zero returns Infinity , which is similar to NaN (not a number).


2 Answers

You're doing integer division.

You need to cast one operand to double.

like image 87
SLaks Avatar answered Sep 20 '22 08:09

SLaks


You are doing an integer division, cast the values to float and change the datatype of the variable bmi to float.

Like this:

float bmi = (float)weight/(float)(height*height);

You should also change the return type of your method public int computeBMI() to float.

I recommend you to read this stackoverflow question.

Here you have a list of the Primitive Data Types in Java with its full description.

Hope it helps!

like image 23
Cacho Santa Avatar answered Sep 23 '22 08:09

Cacho Santa