HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaModerate

FizzBuzz Implementation in Java

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
implementationjavafizzbuzz

Problem

Fairly new to learning interview questions and I saw this one and gave it a shot. I would very much appreciate some constructive criticism of how I went about it and what you would tell me if you were the interviewer and watched me implement it this way.

public class FizzBuzz {
  public static void main(String[] args) {
    // Go from 1 to 100
    for (int i = 1; i <= 100; i++) {
      String result = "";
      if (i % 3 == 0) { // If divisible by 3
        result += "Fizz";
      }
      if (i % 5 == 0) { // If divisible by 5
        result += "Buzz";
      }
      // If it was divisible by either 3 or 5 (or both), print Fizz, Buzz, or FizzBuzz accordingly.
      if (i % 3 == 0 || i % 5 == 0) {
        System.out.println(result);
      } else { // Or else just print the integer
        System.out.println(i);
      }
    }
  }

Solution

The point of FizzBuzz is to weed out obviously unqualified candidates, not to over-optimize the solution or to show off. Your code is a fine interview answer.

Make sure that your braces all match up. It would be more conventional to use 4 or 8 spaces per level of indentation.

My main suggestion — and this is an opinionated nitpick — is to tone down the comments, because comments that restate obvious code give the impression that you might be unfamiliar with the language. Experienced programmers never write // Go from 1 to 100 to explain for (int i = 1; i <= 100; i++). If you feel compelled to demonstrate your documentation skills, write some JavaDoc instead.

Context

StackExchange Code Review Q#147583, answer score: 18

Revisions (0)

No revisions yet.