Learn to Program, by Chris Pine

P

Patrick Hummer

Hey everyone I was having a slight problem with one of the examples in
the book. I was doing the '99 beers' example and ran into a problem at
the end. The task asks you to create a prog that will recite the lyrics
for '99 beers on the wall' which seemed fairly easy to do but I wanted
to make it more challenging for myself and make it more grammatically
correct. So I tried to create an if statement to change the word
'bottles' to 'bottle' when bottles = 1. I have seen another example
creating a working solution but requires many more lines of code and I
was trying to do it in a more clever way (maybe it is backfiring). I
just can't figure out why it is not working properly. Anyway here is
the code:

Code:
bottles = 99
bword = ' bottles'
while bottles != 0
puts(bottles.to_s + bword + " of beer on the wall!")
puts(bottles.to_s + bword + " of beer!")
puts("Take one down and pass it around!")
bottles = bottles - 1
puts(bottles.to_s + bword + " of beer on the wall!")
puts ''
if bottles == 1
bword = ' bottle'
else
bword = ' bottles'
end
end

and here is the output that isn't showing up as planned:

2 bottles of beer on the wall!
2 bottles of beer!
Take one down and pass it around!
1 bottles of beer on the wall!

1 bottle of beer on the wall!
1 bottle of beer!
Take on down and pass it around!
0 bottle of beer on the wall!

It doesn't work for the first line with a 1 on it and I wanted it to
switch back to 'bottles' with the zero on the last line. Any thoughts?
 
E

Eleanor McHugh

bottles = 99
bword = ' bottles'
while bottles != 0
puts(bottles.to_s + bword + " of beer on the wall!")
puts(bottles.to_s + bword + " of beer!")
puts("Take one down and pass it around!")
bottles = bottles - 1
puts(bottles.to_s + bword + " of beer on the wall!")
puts ''
if bottles == 1
bword = ' bottle'
else
bword = ' bottles'
end
end

You need to reorder your logic slightly so that bword is changed as
soon as the bottle count is decremented:

bottle = 99
bword = 'bottles'
while bottles != 0
puts(bottles.to_s + bword + " of beer on the wall!")
puts(bottles.to_s + bword + " of beer!")
puts("Take one down and pass it around!")
bottles = bottles - 1
if bottles == 1
bword = ' bottle'
else
bword = ' bottles'
end
puts(bottles.to_s + bword + " of beer on the wall!")
puts ''
end


Ellie

Eleanor McHugh
Games With Brains
http://slides.games-with-brains.net
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,598
Members
45,152
Latest member
LorettaGur
Top