Tuesday, August 31, 2010

FizzBuzz

On the first day of class we were presented with a quick Java programing quiz called FizzBuzz.  A simple program which we were only given 5 minutes to complete on paper.

Unfortunately I came up a few lines short before I handed it in so I wrote it again later on that day taking about 6 minutes complete after starting up Eclipse:


/**
 * FizzBuzz program. 
 * Prints numbers 1 to 100.
 * If the number is divisable by 3 it prints out "Fizz".
 * If the number is divisable by 5 it prints out "Buzz".
 * If the number is divisable by 15 it prints out "FizzBuzz."
 * 
 * Time taken to write 4 minutes.
 * @author Tony Gaskell
 *
 */
public class FizzBuzz {
  public static void main(String[]args){
    for (int i = 1; i <=100; i++){
      if (i % 3 == 0){             // <-- If the number is divisible by 3...
        System.out.print("Fizz");
      }
      if (i % 5 == 0){             // <-- If the number is divisible by 5...
        System.out.print("Buzz");
      }
      else if (i % 3 != 0){        // <-- If the number not divisible by 3 or 5...
        System.out.print(i);
      }
      System.out.print("\n");      // <-- UGH
    }
  }
}




Nothing had really changed since the code I had written in class except for being able to get in the last else statement.

The program is a simple for loop that counts from 1 to 100.  If the counter i is ever divisible by 3 it will print Fizz to the screen, and Buzz if it is divisible by 5.  I decided to do as few checks as possible so that the program could run slightly faster.  By default if the number is divisible by both 3 and 5 it will print out FizzBuzz on one line since there's no new line characters being printed out at each check.  The final else statement catches everything that is not divisible by 15 and prints the appropriate number to the screen.  At the end of each iteration a new line character is printed.

I think the program turned out pretty well for the time that was put into it.  
I'm not too fond of the line: System.out.print("\n"); since it's not very elegant, but it gets the job done I suppose.

Luckily I have used Eclipse before in my second semester of Java programming, so I was already pretty familiar with the interface.

I was pretty surprised that I could recall my Java since I haven't touched the language in a little over eight months, but I guess the syntax is pretty much the same thing as C.

1 comment:

  1. (1) png image does not display at top of posting.

    (2) see 'println'.

    ReplyDelete