| 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: 536
|
|
|
[ 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: 32708
|
|
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: 32708
|
|
|
And when you have understood such a problem, you will find it easier when a similar problem occurs in future.
|
 |
 |
|
|
subject: Head First Java - Beer question
|
|
|