Bottles of Beer Song via Java

PA300108
Creative Commons License photo credit: NUCO

This programming challenge is from the Head First Java book, which I studied and practiced spring 2009. The end result itself is not terribly sexy, but I liked the algorithm construction process. My programming curriculum changed course during the first year, and they eliminated our Java classes. I was still curious about Java, so I took it upon myself to self-learn Java. This was one of my first products.

I post these self-instructional challenges for a few reasons. One is to demonstrate my programming learning, experience, and progression. Another reason is to make sure my code and solutions are indexed by search engines, so that other beginning programmers may get help if they need it. Finally, self-instructional challenges are interesting and different than academic challenges because I sought, discovered, and performed them on my own volition without anyone else telling me to do so. I did it because I wanted to learn and practice.

Challenge: Create a simple program which outputs the classic “99 Bottles of Beer” song, counting down from 99 to 0 bottles. In addition to outputting the correct number of bottles in each chorus, output the correct plural or singular form of “bottle” where appropriate to the number remaining. When there are no more bottles left then state final line.

My solution:

package bottlesofbeer;

/**
 *
 * @author kirk
 */
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // initialize starting number of bottles on wall
        int beerNum = 99;

        // initialize plural form of bottle used most often
        String word = "bottles";

        while (beerNum > 0) {
            // if only 1 bottle is left then change to singular form
            if (beerNum == 1) { word = "bottle"; }

            // output song chorus using current variable states
            System.out.println(beerNum + " " + word + " of beer on the wall,");
            System.out.println(beerNum + " " + word + " of beer!");
            System.out.println("Take one down, pass it around.");

            // decrement beerNum cuz we took one down and passed it around
            beerNum--;
            if (beerNum == 1) { word = "bottle"; }

            // so long as there are still bottles on the wall
            if (beerNum > 0) {
                System.out.println(beerNum + " " + word + " of beer on the wall!");
                System.out.println();
            }
            // when there are no more bottles on the wall
            else {
                System.out.println("No more bottles of beer on the wall!");
            } // ends if/else
        } // ends while loop
    } // ends main method
} // ends class

Here is the output:

99 Bottles of Beer Song output via Java

99 Bottles of Beer Song output via Java

  • Share/Bookmark




Leave a Reply