|
| 1 | +package examples.longerExamples |
| 2 | + |
| 3 | +/** |
| 4 | + * This example implements the famous "99 Bottles of Beer" program |
| 5 | + * See http://99-bottles-of-beer.net/ |
| 6 | + * |
| 7 | + * The point is to print out a song with the following lyrics: |
| 8 | + * |
| 9 | + * The "99 bottles of beer" song |
| 10 | + * |
| 11 | + * 99 bottles of beer on the wall, 99 bottles of beer. |
| 12 | + * Take one down, pass it around, 98 bottles of beer on the wall. |
| 13 | + * |
| 14 | + * 98 bottles of beer on the wall, 98 bottles of beer. |
| 15 | + * Take one down, pass it around, 97 bottles of beer on the wall. |
| 16 | + * |
| 17 | + * ... |
| 18 | + * |
| 19 | + * 2 bottles of beer on the wall, 2 bottles of beer. |
| 20 | + * Take one down, pass it around, 1 bottle of beer on the wall. |
| 21 | + * |
| 22 | + * 1 bottle of beer on the wall, 1 bottle of beer. |
| 23 | + * Take one down, pass it around, no more bottles of beer on the wall. |
| 24 | + * |
| 25 | + * No more bottles of beer on the wall, no more bottles of beer. |
| 26 | + * Go to the store and buy some more, 99 bottles of beer on the wall. |
| 27 | + * |
| 28 | + * Additionally, you can pass the desired initial number of bottles to use (rather than 99) |
| 29 | + * as a command-line argument |
| 30 | + * |
| 31 | + * @author Edwin.Wu |
| 32 | + * @version 2018/2/3 上午11:56 |
| 33 | + * @since JDK1.8 |
| 34 | + */ |
| 35 | +fun main(args: Array<String>) { |
| 36 | +// if (args.isEmpty()) { |
| 37 | +// println(99) |
| 38 | +// } else { |
| 39 | +// printBottles(args[0].toInt()) |
| 40 | +// } |
| 41 | + |
| 42 | + printBottles(5) |
| 43 | +} |
| 44 | + |
| 45 | +fun printBottles(bottleCount: Int) { |
| 46 | + if (bottleCount <= 0) { |
| 47 | + println("No bottles - no song") |
| 48 | + return |
| 49 | + } |
| 50 | + |
| 51 | + println("The \"${bottlesOfBeer(bottleCount)}\" song\n") |
| 52 | + |
| 53 | + var bottles = bottleCount |
| 54 | + while (bottles > 0) { |
| 55 | + var bottlesOfBeer = bottlesOfBeer(bottles) |
| 56 | + print("$bottlesOfBeer on the wall, $bottlesOfBeer.\nTake one down, pass it around, ") |
| 57 | + bottles-- |
| 58 | + println("${bottlesOfBeer(bottles)} on the wall.\n") |
| 59 | + } |
| 60 | + println("No more bottles of beer on the wall, no more bottles of beer.\n" + |
| 61 | + "Go to the store and buy some more, ${bottlesOfBeer(bottleCount)} on the wall.") |
| 62 | +} |
| 63 | + |
| 64 | +fun bottlesOfBeer(count: Int): String = |
| 65 | + when (count) { |
| 66 | + 0 -> "no more bottles" |
| 67 | + 1 -> "1 bottle" |
| 68 | + else -> "$count bottles" |
| 69 | + } + " of beer" |
| 70 | + |
| 71 | +/* |
| 72 | + * An excerpt from the Standard Library |
| 73 | + */ |
| 74 | + |
| 75 | + |
| 76 | +// This is an extension property, i.e. a property that is defined for the |
| 77 | +// type Array<T>, but does not sit inside the class Array |
| 78 | +val <T> Array<T>.isEmpty: Boolean get() = size == 0 |
0 commit comments