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

Code review request for fizz buzz

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

Problem

Okay code reviewers, I need you to make my FizzBuzz code even better. Any suggestions for improvement, optimizations, etc.

public final class FizzBuzz {

    private FizzBuzz() {};

    /**
     * comparisons for a multiple of 3 = 2
     * comparisons for a multiple of 5 = 2
     * comparisons for a multiple of 15 = 2
     * 
     */
    public static void fizzBuzzBad() {
        // most common thought process
        for (int n = 1; n < 20; n++) {
            if (n % 3 == 0) {
                System.out.print("fizz");
            } else if (n % 5 == 0) {
                System.out.println("buzz");
            } else {
                System.out.println("\n" + n);
            }
        }
    }

    /**
     * comparisons for a multiple of 3 = 2
     * comparisons for a multiple of 5 = 2
     * comparisons for a multiple of 15 = 1 <--- here is the savings.
     * 
     * This saves the number of comparison for 15's.
     */
    public static void fizzBuzzBetter() {
        // most common thought process
        for (int n = 1; n < 20; n++) {
            if (n % 15 == 0) {
                System.out.print("fizzbuzz");
            } else if (n % 3 == 0) {
                System.out.print("buzz");
            } else if (n % 5 == 0) {
                System.out.println("fizz");
            } else {
                System.out.println("\n" + n);
            }
        }
    }

    public static void main(String[] args) {
        fizzBuzzBad();
        System.out.println("--------------------------------------------");
        fizzBuzzBetter();
    }

}

Solution

In both versions, your policy on printing newlines is inconsistent. With fizzBuzzBetter(), all of your cases are mutually exclusive, so they should all be System.out.println(...) calls, and there is no need to prepend "\n".

Your fizzBuzzBad() is wrong: it won't print "fizzbuzz" for multiples of 15.

Anything that can easily be parameterized ought to be. Instead of hard-coding 20, your functions should take a max parameter that is passed from main.

Context

StackExchange Code Review Q#32627, answer score: 4

Revisions (0)

No revisions yet.