-1

I am trying to code a basic command line BMI Calculator in Java and for some reason every time I run the code and enter my height and weight, 0 is outputted. Please help me understand where I have made a mistake.

import java.util.Scanner;
public class Chap2 {
    public static void main(String[] args){
        Scanner reader = new Scanner(System.in);
        System.out.println("Enter your height in inches: ");
        int myHeight = reader.nextInt();
        System.out.println("Enter your weight in lbs: ");
        int myWeight = reader.nextInt();
        int Bmi = (myWeight/myHeight/myHeight)*703;
        System.out.println("Your BMI is " + Bmi + ".");
}
}

And my output is as follows:

Enter your height in inches: 
68
Enter your weight in lbs: 
180
Your BMI is 0.
  • Things will be different if you change to `(703*myWeight/myHeight/myHeight)`. The root cause is described in the duplicate. – Erwin Bolwidt Jul 12 '17 at 00:52

1 Answers1

0

You are dividing int with int, thus the result is a rounded int. Cast to double before calculation to get exact results.

double bmi = ((double) myWeight / myHeight / myHeight) * 703;
A1m
  • 1,579
  • 1
  • 14
  • 33
  • why does dividing int with int return 0? – Arjun Patel Jul 12 '17 at 00:52
  • Cause the result will be a `int` again and this will be rounded. The frist calculation is `0` then and thus the next is that also. Read further here: [link](https://stackoverflow.com/questions/4685450/why-is-the-result-of-1-3-0) – A1m Jul 12 '17 at 00:54
  • And btw do not capitalize your variable names! :) – A1m Jul 12 '17 at 00:58