Home › Learn › Java › Loops

FizzBuzz

Lesson 15 of 40. The classic loop-and-conditions exercise.

FizzBuzz: for the numbers 1 to n, print Fizz for multiples of 3, Buzz for multiples of 5, FizzBuzz for multiples of both, and the number otherwise. The trap is the order of the tests: 15 % 3 == 0 is true, so testing 3 first prints Fizz for 15. Test the combined case first, or build the word from two independent tests and print the number when the word is empty.

Splitting the work into a method that returns the word for one number and a loop that prints keeps each part easy to check, which is the habit the rest of the course builds on.

String word = "";
if (n % 3 == 0) word += "Fizz";
if (n % 5 == 0) word += "Buzz";
if (word.isEmpty()) word = String.valueOf(n);

Your task

Write static String fizzBuzz(int n) returning the word for one number ("Fizz", "Buzz", "FizzBuzz", or the number as text). Then make main print fizzBuzz(i) for i from 1 to 15, one per line.

Hint 1

Build the word from two ifs as in the example; String.valueOf(n) turns the number into text.

Hint 2

for (int i = 1; i <= 15; i++) System.out.println(fizzBuzz(i));

Show the solution
public class Main {
    static String fizzBuzz(int n) {
        String word = "";
        if (n % 3 == 0) {
            word += "Fizz";
        }
        if (n % 5 == 0) {
            word += "Buzz";
        }
        if (word.isEmpty()) {
            word = String.valueOf(n);
        }
        return word;
    }

    public static void main(String[] args) {
        for (int i = 1; i <= 15; i++) {
            System.out.println(fizzBuzz(i));
        }
    }
}

    Compiles with OpenJDK javac and TeaVM, both compiled to WebAssembly (7 MB download the first time, then cached), and runs in this tab; nothing is sent anywhere.