Friday, January 9, 2015

Beersong

So today I fixed a program that prints the words to the Beer Song, AKA 99 Bottles of  Beer.
Original code:

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");
            }
        }
    }
}

This works well, except towards the end it prints "Pass it around, 1 bottles of beer on the wall" because the variable "word" is updated at the beginning of the loop rather than after the beer count changes.

public class BeerSong {
    public static void main(String[] args) {
        int beernum = 99;
        String word = "bottles";
        
        while (beernum>0) {
            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==1) {
                word = "bottle";
            }
            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");
            }
        }
    }
}

No comments:

Post a Comment