patternjavaMinor
Beer song excercise
Viewed 0 times
excercisesongbeer
Problem
I'm reading the book Head First Java and got an assignment to re-create the 99 Bottles of Beer song according to those lyrics found in the URL. I've had to do this with a Java while loop.
My problems with the code:
class SecondBeerSong {
public static void main(String[] args) {
int beerBottles = 99;
String word;
while(beerBottles >= 0) {
word = "bottles";
if(beerBottles != 0) {
System.out.println(beerBottles + " " + word + " of beer on the wall, "+ beerBottles + " " + word + " of beer." );
beerBottles--;
if(beerBottles == 1) {
word = "bottle";
}
if(beerBottles > 0) {
System.out.println("Take one down and pass it around, " + beerBottles + " " + word +" of beer on the wall.");
} else {
System.out.println("Take one down and pass it around, no more " + word +" of beer on the wall.");
}
} else {
System.out.println("No more " + word + " of beer on the wall, no more " + word + " of beer.");
System.out.println("Go to the store and buy some more, 99 bottles of beer on the wall.");
break;
}
System.out.println();
}
}
}My problems with the code:
- Lack of readability
- To many if statements for string building
- It's confusing
- Not "object-oriented"
- The
whileloop gets ended with abreak
Solution
Move something outside of the loop
The main problem is that you are handling 0 and 1 bottles inside the loop, therefore making the whole loop more convoluted for one-shot conditions.
I suggest a loop to handle 99 to 2 and handling 1 and 0 manually:
As you have seen above, I used a
The main problem is that you are handling 0 and 1 bottles inside the loop, therefore making the whole loop more convoluted for one-shot conditions.
I suggest a loop to handle 99 to 2 and handling 1 and 0 manually:
for (int n = 99; n >= 2; n--) {
System.out.println("Take one down and pass it around, " + n + " bottles of beer on the wall.");
System.out.println("Take one down and pass it around, " + (n - 1) + " more bottles of beer on the wall.");
}
System.out.println("1 and 0 bottles text, verbatim");for loopAs you have seen above, I used a
for loop as it is recommended over while when you already know how many times you'll loop as it groups together start, condition and step. Making the code shorter and more organized.Code Snippets
for (int n = 99; n >= 2; n--) {
System.out.println("Take one down and pass it around, " + n + " bottles of beer on the wall.");
System.out.println("Take one down and pass it around, " + (n - 1) + " more bottles of beer on the wall.");
}
System.out.println("1 and 0 bottles text, verbatim");Context
StackExchange Code Review Q#111498, answer score: 9
Revisions (0)
No revisions yet.