*
The moose likes Beginning Java and the fly likes Head First Java - Beer question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Head First Java - Beer question" Watch "Head First Java - Beer question" New topic
Author

Head First Java - Beer question

Narin Kittikul
Greenhorn

Joined: Jul 29, 2009
Posts: 3
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

Joined: Jul 15, 2009
Posts: 537




[ SCJP 6.0 - 90% ] , JSP, Servlets and Learning EJB.
Try out the programs using a TextEditor. Textpad - Java 6 api
Narin Kittikul
Greenhorn

Joined: Jul 29, 2009
Posts: 3
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

Joined: Oct 13, 2005
Posts: 38064
    
  22
Nice to get a problem solved, isn't it?

And welcome to JavaRanch
Narin Kittikul
Greenhorn

Joined: Jul 29, 2009
Posts: 3
Thanks. Yeah, it's very satisfying to finally figure it out
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38064
    
  22
And when you have understood such a problem, you will find it easier when a similar problem occurs in future.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Head First Java - Beer question
 
Similar Threads
Beersong
Head first Beersong
Back Again with a program...
Beer song HomeWork
Why does this program start from 60 bottles of Beer and not 99