my dog learned polymorphism*
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


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Please Help" Watch "Please Help" New topic
Author

Please Help

Mike Nguyen
Greenhorn

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
Saloon Keeper

Joined: Jul 29, 2008
Posts: 3017
    
  35

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.


Founder of ExamLab and Systemup
See how I can help you to become an awesome programmer
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11153
    
  16

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
Greenhorn

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

Joined: Oct 13, 2005
Posts: 37945
    
  22
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
 
Similar Threads
Help making my BMI calculator more complex?
try...catch blocks giving <identifier> expected error
Comparison expresions
So, which of these would be...
DEbugging