Write a program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”.

Thursday, January 5, 2012

#2 - Is That Your Final Answer?

When it comes to minor tweaks in the presentation of the problem, there is more than one way to make "the smallest change." Rather than printing out the result immediately we can defer the printing and keep an answer in a variable, changing it as needed.

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.

1 comment:

  1. I like this approach.. but I have to admit if i wrote the code it would look like this:


    public 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);
    }
    }
    }

    ReplyDelete