TASK & PURPOSE:
The task was to implement the FizzBuzz program:
“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”.”
PROBLEMS:
The main problem I ran into while doing this was creating the program using the test case development style described earlier. I had a hard time linking the test class up to the FizzBuzz class. It would not recognize my getValue() function and it was confusing me.
SOLUTIONS:
I finally realized the simple solution to my problem was to use ‘FizzBuzz.getValue()’ instead of just ‘getValue()’. This also brought upon another error that was fixed (using hints from eclipse!) by inserting ‘import static org.junit.Assert.*;’ Eclipse is wonderful.
For me doing this program was a nice little refresher into programming again in java. It also was really nice to go in and use the JUnit test case development in Eclipse. Although test-driven development is a bit overkill for a simple program like FizzBuzz, I can see how on a larger scale this development system could be really efficient. It would be easier to solve a large problem by first testing out and solving smaller problems. I like the simplicity of this. It seems like it would lead to less bugs and smoother overall development.
SOURCE CODE:
FizzBuzzTest.java
import static org.junit.Assert.*;
import org.junit.Test;
public class FizzBuzzTest {
@Test
public void testFB() {
assertEquals("Test 1", "1", FizzBuzz.getValue(1));
assertEquals("Test 3", "Fizz", FizzBuzz.getValue(3));
assertEquals("Test 5", "Buzz", FizzBuzz.getValue(5));
assertEquals("Test 15", "FizzBuzz", FizzBuzz.getValue(15));
assertEquals("Test 100", "Buzz", FizzBuzz.getValue(100));
}
}
FizzBuzz.java
/**
* A Simple program that runs through the numbers 1 - 100,
* printing either "Fizz" for multiples of 3, "Buzz" for
* multiples of 5, "FizzBuzz" for multiples of both, or just
* the number itself for all others.
*
* @author Tyler Wolff
*/
public class FizzBuzz {
public static String getValue(int iNum) {
if ((iNum % 3 == 0) && (iNum % 5 == 0)) {
return "FizzBuzz";
} else if (iNum % 3 == 0) {
return "Fizz";
} else if (iNum % 5 == 0) {
return "Buzz";
} else {
return String.valueOf(iNum);
}
}
public static void main(String[] args) {
for (int i = 1; i <= 100; i++) { System.out.println(getValue(i));
}
}
}