Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Head First Java - Beer question

 
Narin Kittikul
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, everyone. I'm just starting out using Java, and I'm having some trouble correcting the error in the book's Beer song exercise. I've seen topics related to the Beer song question before, but mine is more about why the solution works as it does.

So, the original code is this:

public class BeerSong
{
public static void main(String[] args)
{
int beerNum = 99;
String word = "bottles";
while (beerNum > 0)
{
if (beerNum == 1)
{ word = "bottle"; }


System.out.println(beerNum + " " + word + " of beer on the wall");
System.out.println(beerNum + " " + word + " of beer.");
System.out.println("Take one down.");
System.out.println("Pass it around.");
beerNum = beerNum - 1;

if (beerNum > 0)
{ System.out.println(beerNum + " " + word + " of beer on the wall"); }


else
{ System.out.println("No more bottles of beer on the wall"); }
}
}
}


The problem with the original is that the final lines read:

One bottles of beer on the wall
One bottle of beer
Take one down.
Pass it around.
No more bottles of beer on the wall.

I spent a good deal of time trying to fix that problem, only to look it up and find that the simple moving of the

if (beerNum == 1)
{ word = "bottle"; }


to under the
beerNum = beerNum - 1;


fixed the whole problem.

However, I can't figure out why it fixes it. Can anyone please explain that to me?
 
Nitish Bangera
Ranch Hand
Posts: 537
Eclipse IDE Java Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


 
Narin Kittikul
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ah, I get it now. It took a while, I had to go line by line, but now I see how the process works. Thank you.
 
Campbell Ritchie
Sheriff
Posts: 48652
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Nice to get a problem solved, isn't it?

And welcome to JavaRanch
 
Narin Kittikul
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks. Yeah, it's very satisfying to finally figure it out
 
Campbell Ritchie
Sheriff
Posts: 48652
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And when you have understood such a problem, you will find it easier when a similar problem occurs in future.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic