0

I just started learning java and I thought I'd build a BMI program for my friend.
But whenever I enter my height and mass it returns 0 rather than the BMI value.

import java.util.Scanner;

public class calculator {
public static void main(String[] args) {
    int a, kg, height;
        Scanner scanner = new Scanner(System.in);

        System.out.println("What is your height in meter?");
        height = scanner.nextInt();
        System.out.println("What is your Mass in KG?");
        kg = scanner.nextInt();

        height = height * height;
        double BMI = kg/height;
        System.out.println(BMI);
    }
}
Yunnosch
  • 26,130
  • 9
  • 42
  • 54

1 Answers1

1

Your code uses integer division, which results in 0 for anything divided by some greater nubmer.
If you force floating point division it will work.

double BMI = 1.0*kg/height;

The above assumes that you are entering integers (because otherwise you would not get the result of 0 you describe).

If you want your program to also handle floating point input correctly, do as recommended by Aaalexander in comments and use double typed variables.

double a, kg, height;
/* ... */
height = scanner.nextDouble();
/* ... */
kg = scanner.nextDouble();
Yunnosch
  • 26,130
  • 9
  • 42
  • 54