Wednesday, August 27, 2008

FizzBuzz programming exercise

This is the first blog post of many to come, so it may be a little rough around the edges. I'm currently attending a course called ICS 413 - Software Engineering, and this class teaches what I hope to be efficient programming practices that I can apply in real life, a stark contrast to my other courses which I feel are more like intellectual exercises rather than practical examples.

The Exercise
A simple exercise to start us off, this one has us refreshing our Java skills by programming something relatively simple. The output has to be a count from 1 to 100, one number per line, except that if the number is a multiple of 3, the output is "Fizz", when it's a multiple of 5, it's "Buzz", and when it's a multiple of 3 and 5, it's "FizzBuzz". This program, though deceptively simple, was a good measure to see how our Java knowledge has stood the test of time, since for most of us, the last Java programming assignment we've had was in ICS 211 almost two years ago.

The Process
Of course, the foundation of any good programmer is a good IDE, and Eclipse is the IDE we're using for the course. I've used Eclipse before back in the introductory Java courses, and the developers have made some huge improvements to both the speed and the interface of the program. Unfortunately, they also made it display a welcome screen that blocks the windows behind it, and it's not immediately obvious that you have to close this window to see anything behind it. When I tried to create a new project and a new class, I thought something was wrong when the welcome screen didn't change until I realized that I had to close it first. Not exactly very intuitive if you ask me, and a slight issue where HCI is concerned.

Fortunately, the actual programming itself went quite smoothly except for one problem where I forgot how to declare a method with no return value. At first I was trying to use public static null FizzBuzz(), which didn't work. A quick Google search reminded me that it's supposed to be void, not null. For the past few years, I've been programming mostly in Visual Basic for an Access database so I'm a little rusty at Java, but I have to say, forgetting something as simple as this is pretty shameful for me. The entire program from beginning to end took 8 minutes and 2 seconds to write and it served as a nice reminder that I need to brush up on my Java syntax, something I'm sure I'll be getting a lot of practice with from this course.

Code
public class ClassFizzBuzz {
public static void FizzBuzz() {
for(int i = 1; i <= 100; i++)
{
if((i % 5 == 0) && (i % 3 == 0)) {
System.out.println("FizzBuzz");
}
else if (i % 5 == 0) {
System.out.println("Buzz");
}
else if (i % 3 == 0) {
System.out.println("Fizz");
}
else
{
System.out.println(String.valueOf(i));
}
}
}

public static void main(String[] args) {
FizzBuzz();
}
}

No comments: