stytown stytown - 5 months ago 8
Java Question

Raising a number to a power in Java

Here is my code. For some reason my BMI is not calculated correctly.
When I check the output on a calculator for this :

(10/((10/100)^2)))
I get 1000, but in my program, I get 5. I'm not sure what I am doing wrong. Here is my code:

import javax.swing.*;

public class BMI {
public static void main(String args[]) {
int height;
int weight;
String getweight;
getweight = JOptionPane.showInputDialog(null, "Please enter your weight in Kilograms");
String getheight;
getheight = JOptionPane.showInputDialog(null, "Please enter your height in Centimeters");
weight = Integer.parseInt(getweight);
height = Integer.parseInt(getheight);
double bmi;
bmi = (weight/((height/100)^2));
JOptionPane.showMessageDialog(null, "Your BMI is: " + bmi);
}
}

Answer

^ in java does not mean to raise to a power. It means XOR.

You can use java's Math.pow()


And you might want to consider using double instead of int—that is:

double height;
double weight;

Note that 199/100 evaluates to 1.