Codiqo

Learn Java · lesson 21 of 61 · about 9 minutes

Project: FizzBuzz

Before the film, the screen plays a counting game: check how far the audience wants to go, then count with Fizz for 3s and Buzz for 5s.

What you'll learn

  • Combine loops and conditions
  • Order checks correctly
  • Build output text

The game on screen

While the adverts run, the screen plays a game with the audience. Someone picks how far to count, from 1 to 30, and the screen shows every number: Fizz for a multiple of 3, Buzz for a multiple of 5, FizzBuzz for both. It's the classic interview puzzle, FizzBuzz.

The rules

For each number from 1 to 15:

  • divisible by 3 and 5: FizzBuzz
  • divisible by 3: Fizz
  • divisible by 5: Buzz
  • otherwise the number

Building the word from pieces avoids a special FizzBuzz case.

FizzBuzz

public class Main {
    public static void main(String[] args) {
        for (int i = 1; i <= 15; i++) {
            String word = "";
            if (i % 3 == 0) word += "Fizz";
            if (i % 5 == 0) word += "Buzz";
            System.out.print((word.isEmpty() ? String.valueOf(i) : word) + " ");
        }
        System.out.println();
    }
}

Output

1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz

The screen checks the number first

public class Main {
    public static void main(String[] args) {
        int count = 5;
        if (count < 1 || count > 30) {
            System.out.println("The screen only counts from 1 to 30.");
        } else {
            for (int n = 1; n <= count; n++) {
                String word = "";
                if (n % 3 == 0) {
                    word += "Fizz";
                }
                if (n % 5 == 0) {
                    word += "Buzz";
                }
                System.out.println(word.isEmpty() ? String.valueOf(n) : word);
            }
            System.out.println("Enjoy the film!");
        }
    }
}

Output

1
2
Fizz
4
Buzz
Enjoy the film!

Tip

The building approach needs no special FizzBuzz case: 15 collects both pieces by itself. Adding a new rule, like 7 for Bazz, is one more line.

Now try it yourself

This lesson is free in Codiqo, with 8 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.