programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
• Liutauras Vilda
• Campbell Ritchie
• Tim Cooke
• Bear Bibeault
• Devaka Cooray
Sheriffs:
• Jeanne Boyarsky
• Knute Snortum
• Junilu Lacar
Saloon Keepers:
• Tim Moores
• Ganesh Patekar
• Stephan van Hulst
• Pete Letkeman
• Carey Brown
Bartenders:
• Tim Holloway
• Ron McLeod
• Vijitha Kumara

# Division in Java

Greenhorn
Posts: 7
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);
int weight = input.nextInt();
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)

Author and ninkuma
Marshal
Posts: 66806
168
Welcome to the Ranch,

What is it you mean by "didn't work"?

Ranch Hand
Posts: 116
2
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:

Chago Bowers
Greenhorn
Posts: 7
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

Marshal
Posts: 60168
188
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.