public class FizzBuzz02 { public static void main(String[] args) { for (int i = 1; i <= 100; i++) { String answer = Integer.toString(i); if (i % 3 == 0) { answer = "Fizz"; } if (i % 5 == 0) { answer = "Buzz"; } if ((i % 3 == 0) && (i % 5 == 0)) { answer = "FizzBuzz"; } System.out.println(answer); } } }
This example allows two important changes, actually. The first is the introduction of a variable, and the changing of the variable Once we are done deciding what the result should be we can then print out the result of the variable.
The second important change is that we can consider each condition on its own. Since the most general cases are considered first and then the most specific are considered later. Since the most specific one is considered last, it can overwrite the previous answer. When you add these two items together, you can see that the variable will be set once, twice, or four times. Never three.
Another way to think of this is a game show. Rather than playing Jeopardy, where only the first answer given is accepted, we are playing Who Wants to Be a Millionaire, where the last answer given is accepted. Contestants routinely change their answers but the only answer that matters is the last answer.
I like this approach.. but I have to admit if i wrote the code it would look like this:
ReplyDeletepublic class FizzBuzz02 {
public static void main(String[] args) {
for (int i = 1; i <= 100; i++) {
String answer;
if (i % 3 == 0) {
answer = "Fizz";
}
if (i % 5 == 0) {
answer += "Buzz";
}
System.out.println(answer);
}
}
}