• Post Reply Bookmark Topic Watch Topic
  • New Topic

Division in Java  RSS feed

 
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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);
 
Author and ninkuma
Marshal
Posts: 66307
152
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch,

What is it you mean by "didn't work"?
 
Ranch Hand
Posts: 116
2
Eclipse IDE Java PHP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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: 56600
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!