Sunday, August 30, 2009

FizzBuzz Experience

FizzBuzz is a good startup assignment. In short, the goal is to print a number from 1 to 100 on each line and if the number is a multiple of 3 print Fizz, if the number is a multiple of 5 print Buzz, and if a number is a multiple of 3 & 5 print FizzBuzz.

It took me about 15 minutes to implement the FizzBuzz in which most of the time spent on setting up a new java project in Eclipse. Rewritten the code did not take long.

When I started using Eclipse for the first time, I encountered a lot of minor challenges. One of the challenges was setting up the java project and adding new java class into the package.

After finishing the main class, I also had problem when adding the JUnit test case to the package. It took a while to get the right syntax for assertEquals and get the TestFuzzBuzz pass.

Since it’s been a long time from my undergrad that I’ve coded Java, I’ve also encountered a lot of syntax error and mistype the keywords. By using Eclipse, it's a lot easier to code, compile, and package Java project compare to using command prompt when I first learned Java programming 7 years ago.

Here’s my code for the FizzBuzz:


public class FizzBuzz {

    public static void main(String[] args) {
        for (int i=1; i<=100; i++) {
            System.out.println(getFizzBuzz(i));
        }
    }

    static String getFizzBuzz(int i) {
        if ((i%3==0) && (i%5==0))
            return "FuzzBuzz";
        else if (i%3==0) return "Fizz";
        else if (i%5==0) return "Buzz";
        return Integer.toString(i);     
    }
}

Here's my code for the JUnit test case:

import static org.junit.Assert.assertEquals;

import org.junit.Test;

public class TestFuzzBuzz  {
    @Test
    public void Testfuzz () {
        assertEquals("1",FizzBuzz.getFizzBuzz(1));
        assertEquals("Fizz",FizzBuzz.getFizzBuzz(3));
        assertEquals("FuzzBuzz",FizzBuzz.getFizzBuzz(15));
        assertEquals("Buzz",FizzBuzz.getFizzBuzz(5));        
    }
}

No comments:

Post a Comment