• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Please Help

 
Mike Nguyen
Greenhorn
Posts: 2
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Marshal
Pie
Posts: 4122
195
Chrome Eclipse IDE Google App Engine IntelliJ IDE jQuery Postgres Database Tomcat Server
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
fred rosenberger
lowercase baba
Bartender
Pie
Posts: 12022
25
Chrome Java Linux
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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)

 
Mike Nguyen
Greenhorn
Posts: 2
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you very much. That was it
 
Campbell Ritchie
Sheriff
Pie
Posts: 47300
52
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to JavaRanch

Please avoid thread titles like "Please Help" as explained here.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic