Sunday, January 11, 2015

beersong java head first

Beersong

 I fixed a code that prints the words to the Beer Song.
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, towards the end it prints "Pass it around, 1 bottles of beer on the wall" because the variable "word" is set at the beginning of the loop rather than after the beer count changes so it  doesn't change the word bottle.

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