Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!

Code Challenge

Rob McBryde
Greenhorn
Posts: 16
Hi All,

I am still on the continuing quest to improve my Java by setting myself challenges to code. Today I was introduced to a simple numbers game called "FizzBuzz" which I have tried to capture in Java code.

The simple premise is to count through whole numbers from 1 to 100, printing them to the console. However, if the number is a multiple of 3 the word "Fizz" is printed instead of that number. If the number is divisible by 5 then the word "Buzz" is printed in that numbers place. If the number is divisible by both 3 and 5 then the word "FizzBuzz" is printed.

For example:
1
2
Fizz
3
4
Buzz
.
.
.
14
FizzBuzz
16

I have completed my code in a class called FizzBuzz containing one void method called play() that doesn't take any arguments. Was wondering if anyone would care to try this simple task themselves and report back on their attempt. I have attached my code below but please attempt it yourself before looking at my solution. I would welcome any constructive criticism on my code as always as I find this is the best way to learn.

Campbell Ritchie
Sheriff
Posts: 48968
60
That looks all right to me.

You could try if (i % 3 == 0) { answer = "fizz"; } else { answer = ""; } and miss out the assignment at the beginning of the loop
You could also try if (answer.length() == 0) { . . . } else { . . . } at the end.

But those are only minor points.

marc weber
Sheriff
Posts: 11343
Rob McBryde wrote:...please attempt it yourself before looking at my solution...

For better or worse, my logic was the same as yours.

Just one comment: Your variable "answer" is only needed within the scope of the for loop, so there's no need to declare it outside of that.

Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15284
39
Some background about the FizzBuzz question.

A small comment about line 33:

Why are you using equalsIgnoreCase here instead of just equals? Can an empty string be upper case or lower case?

Stefaan Dutry
Ranch Hand
Posts: 32
Another small comment about line 33.
When comparing a String variable with a string literal it's always best to start with the literal as it avoids any NullPointerException if the variable were null.

I know this couldn't happen here, but it's just a good habit to do so.