[Logo]
Forums Register Login
Division in Java
I was trying to execute the following program and the multiplication worked but the division didn't work. Please let me know what I am doing wrong:

import java.util.Scanner;
public class BodyMassIndex {

public static void main(String[] args) {
// Prompt the user for weight and height
// Create a scanner
Scanner input = new Scanner (System.in);
System.out.println("Please enter your weight in pounds");
int weight = input.nextInt();
System.out.println("Please enter your height in inches");
int height = input.nextInt ();
double BMI = weight * (0.45359237)/ (height * 0.0254)*(height * 0.0254);
// the weight * (0.45359237) executed but it wasn't divided by (height * 0.0254)*(height * 0.0254)
System.out.println ("Your BMI is "+BMI);
Welcome to the Ranch,

What is it you mean by "didn't work"?
Hi Chago, welcome to the Ranch!

First, please put all code samples in [ code ] tags to make it easier to read.

About your code, it looks like you need to set the order of operation is your expresstion. To me it looks like you would want the numerator and the denominator to be calculated before the division takes place. For that you might try something like this:
Thank you for the quick response. The extra set of parenthesis around the numerator and denominator did the trick. I'll have to remember this in the future. I was frustrated last night because only the first part of the math weight * 0.45359237 was executed and the rest was just ignored by the compiler. I'll remember to also use code when posting in the future
Welcome again
Try:-

weight * 0.45359237 / height / 0.0254 / height / 0.0254

Remembering that in Java® expressions are evaluated left to right. Complicated explanation here.
Wink, wink, nudge, nudge, say no more ... https://richsoil.com/cards


This thread has been viewed 645 times.

All times above are in ranch (not your local) time.
The current ranch time is
Jun 25, 2018 00:20:34.