The problem is related to the scope of variables. In a non-working example, you declare strings inside the if and else scope. So, when you try to print the values, they go beyond the bounds.
if (beersLeft > 1) { String sOrNot = "s"; // sOrNot scope ends } else { String sOrNot = ""; // sOrNot scope ends } // sOrNot does not exist in this scope. System.out.println(beersLeft+" bottle"+sOrNot+" of beer on the wall, "+beersLeft+" bottle"+sOrNot+" of beer!");
A working example works because when a line is declared at the top of the loop, it has scope in all of this.
while (beersLeft >= 0) { // has scope for rest of loop String sOrNot = ""; .... }
This behavior may seem unintuitive, but it allows you to do things like this:
for (int i = 0; i < 10; i++) { // do something } // The previous i is out of scope, so creates a new one // without having the names "clash" for (int i = 5; i >= 0; i--) { // do something else }
user1599559
source share