programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
• Campbell Ritchie
• Ron McLeod
• Paul Clapham
• Bear Bibeault
• Junilu Lacar
Sheriffs:
• Jeanne Boyarsky
• Tim Cooke
• Henry Wong
Saloon Keepers:
• Tim Moores
• Stephan van Hulst
• Tim Holloway
• salvin francis
• Frits Walraven
Bartenders:
• Scott Selikoff
• Piet Souris
• Carey Brown

# Code Challenge

Greenhorn
Posts: 17
1
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.

Marshal
Posts: 70234
282
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.

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.

Java Cowboy
Posts: 16084
88
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?

Ranch Hand
Posts: 33
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.

 It's a tiny ad. At least, that's what she said. Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton