Download code

Jump to: navigation, search

Back to 99_Bottles_of_Beer_(Java)

Download for Windows: single file, zip

Download for UNIX: single file, zip, tar.gz, tar.bz2

NinetyNineBottles.java

 1 /* The authors of this work have released all rights to it and placed it
 2 in the public domain under the Creative Commons CC0 1.0 waiver
 3 (http://creativecommons.org/publicdomain/zero/1.0/).
 4 
 5 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 6 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 7 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 8 IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 9 CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
10 TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
11 SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
12 
13 Retrieved from: http://en.literateprograms.org/99_Bottles_of_Beer_(Java)?oldid=18905
14 */
15 
16 public class NinetyNineBottles {
17    
18    private static int NUMBER_BOTTLES_OF_BEER_ON_THE_WALL = 99;
19 
20 
21    /**
22     * Print the 99 bottles of beer song to the console.
23     */
24    public void printSong()
25    {
26      int nBottles = NUMBER_BOTTLES_OF_BEER_ON_THE_WALL;
27      while (nBottles > 0) {
28        String verse = "";
29        if (nBottles > 1) verse += verseForNBottles(nBottles);
30        else verse += finalVerse();
31        System.out.println(verse);
32        nBottles--;
33      }
34    }
35 
36    public static void main(String[] args) {
37        NinetyNineBottles nnb = new NinetyNineBottles();
38        nnb.printSong();
39    }
40 
41    //private methods
42 
43    /**
44     * Return verse for N bottles of beer (where N is > 1)
45     * @param nBottles the current number of bottles of beer on the wall.
46     * @return verse appropriate for the number of bottles of beer on the wall.
47     */
48    private String verseForNBottles(int nBottles)
49    {
50       if (nBottles <= 0) return "";
51       String verse = nBottles + " bottles of beer on the wall,\n" +
52            nBottles + " bottles of beer!\n" + 
53            "   Take one down,\n" +
54            "   Pass it around,\n";
55       int bottlesLeft = nBottles - 1;
56       if (bottlesLeft > 1)
57           verse += bottlesLeft + " bottles of beer on the wall!\n\n";
58       else
59           verse += "1 bottle of beer on the wall!\n\n";
60       return verse;
61    }
62  
63    /**
64     * Print final verse for one bottle of beer.
65     * @return the final verse (one bottle of beer on the wall).
66     */
67    private String finalVerse()
68    {
69       return "1 bottle of beer on the wall,\n" +
70            "1 bottle of beer!\n" + 
71            "   Take one down,\n" +
72            "   Pass it around,\n" + 
73            "No more bottles of beer on the wall!\n\n";
74    }
75 }


hijacker
hijacker
hijacker
hijacker