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.
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.