Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
353 views
in Technique[技术] by (71.8m points)

if statement - Logical Error Java - Wrong Computation in BMI

The program lets you input the user's height and weight then outputs the BMI and associated health risk. It converts pounds to kilograms. It also converts the height in feet and inches to meters.

    Scanner scanW = new Scanner (System.in);
    Scanner scanH = new Scanner (System.in);
    
    System.out.println("Enter your weight in pounds: ");
    int weight = scanW.nextInt();
    
    System.out.println("Enter your height in feet followed 
By a space then additional inches");
    String height = scanH.nextLine();

    scanW.close();
    scanH.close();
    
    int heightFt = height.charAt(0);
    int heightInch = height.charAt(2);
    
    int finalHeightFeet = Integer.parseInt(String.valueOf(heightFt));
    int finalHeightInch = Integer.parseInt(String.valueOf(heightInch));
    
    double mass = (double) weight / 2.2;
    double finalHeight = (double) (finalHeightFeet * 0.3048) + (finalHeightInch * 0.0254);
    double BMI = (double) mass / (finalHeight * finalHeight);
    System.out.println("Your BMI is " +BMI);
    
    if (BMI < 18.5)
        System.out.println("Your risk category is UnderWeight");
    else if (BMI < 25)
        System.out.println("Your risk category is Normal Weight");
    else if (BMI < 30)
        System.out.println("Your risk category is Normal Overweight");
    else if (BMI >= 30)
        System.out.println("Your risk category is Obese");
    

the correct BMI and risk category output should be:

Your BMI is 25.013498117367398
Your risk category is Overweight.

but my output would be like this:

Your BMI is 0.22261924276759873
Your risk category is UnderWeight

I'm very sure there's a problem in my formula but I can't seem to find it. Would be very helpful if someone pointed out which is wrong


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You are not parsing the height input correctly.

Suppose you type

5 9

as the height.

You assign "5 9" to height.

You then parse

int heightFt = height.charAt(0);
int heightInch = height.charAt(2);    

which assigns 53 to heightFt and 57 to heightInch (those are the numeric values of the characters '5' and '9').

Try this instead:

String[] height = scanH.nextLine().split (" ");
int heightFt = Integer.parseInt (height[0]);
int heightInch = Integer.parseInt (height[1]);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...