jQuery in Action, 3rd edition
The moose likes Beginning Java and the fly likes Please Help Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Please Help" Watch "Please Help" New topic

Please Help

Mike Nguyen

Joined: Sep 05, 2009
Posts: 2
I have an assignment where I need to compute the Body Mass. My problem is I cannot figure out why the same line of code will compile OK if it's placed inside of an if statement, but when I move it outside of the if statement, I get a compiler error of: "variable bodyIndex might not have been initialized". Any ideas?

the line of code in question is: System.out.printf("\nYour BMI value is %d",bodyIndex);

if (method == 1)
System.out.print("Please enter your weight in pounds: ");
userWeight = input.nextInt();
System.out.print("Please enter your height in inches: ");
userHeight = input.nextInt();
bodyIndex =((userWeight * 703) / (userHeight * userHeight));
System.out.printf("\nYour BMI value is %d",bodyIndex); // <---- Here it is in the if statement. This will compile OK.

Once I take it out of the if statement, I get an error compiling.

Thank you in advance for any assistance given.
Devaka Cooray
ExamLab Creator

Joined: Jul 29, 2008
Posts: 3924

Local variables must be initialized before you can access them. As we can predict here, bodyIndex is a local variable and it will be initialized if and only if method==1
Statements below the if block are executable even though the if condition fails, and bodyIndex is not initialized.

Author of ExamLab ExamLab - a free SCJP / OCPJP exam simulator
What would SCJP exam questions look like? -- Home -- Twitter -- How to Ask a Question
fred rosenberger
lowercase baba

Joined: Oct 02, 2003
Posts: 11955

it's telling you what the problem is. What happens if you're code doesn't enter the if-block? What value will the bodyIndex variable be intialized to?

if you leave the line inside the if-block, then there is no way to use it without it getting initialized first.

You could probably solve this by initializing the int (I assume it's an int)

There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Mike Nguyen

Joined: Sep 05, 2009
Posts: 2
Thank you very much. That was it
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 46362
Welcome to JavaRanch

Please avoid thread titles like "Please Help" as explained here.
I agree. Here's the link: http://aspose.com/file-tools
subject: Please Help
It's not a secret anymore!