Skip to content

Instantly share code, notes, and snippets.

@btforsythe
Created January 24, 2017 20:04
Show Gist options
  • Save btforsythe/7f5ffec52b6fd76de2a342eb9972e457 to your computer and use it in GitHub Desktop.
Save btforsythe/7f5ffec52b6fd76de2a342eb9972e457 to your computer and use it in GitHub Desktop.
public class BeerSong {
public static void main(String[] args) {
int numberOfBottles = 100;
singStanza(numberOfBottles);
/**
* These expressions are equivalent: - numberOfBottles = numberOfBottles
* - 1; - numberOfBottles -= 1; - numberOfBottles--;
*/
while (numberOfBottles >= 67) {
numberOfBottles = numberOfBottles - 1;
singStanza(numberOfBottles);
}
do {
numberOfBottles -= 1;
singStanza(numberOfBottles);
} while (numberOfBottles > 50);
for (int bottleCount = 49; bottleCount > 0; bottleCount--) {
singStanza(bottleCount);
}
System.out.println("No more bottles of refreshing beverage on the waaaaaaall!");
}
private static void singStanza(int numberOfBottles) {
boolean onlyOneBottle = (numberOfBottles == 1);
/**
* We could also do it this way: String descriptor = numberOfBottles >
* 1? "bottles": "bottle";
*
* This is called a ternary operator. You'll like it later.
*/
String descriptor;
if (onlyOneBottle) {
descriptor = "bottle";
} else {
descriptor = "bottles";
}
String bottlesLyric = numberOfBottles + " " + descriptor + " of refreshing beverage";
System.out.println(bottlesLyric + " on the wall.");
System.out.println(bottlesLyric + ". Take one down, pass it around.");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment