Site icon

Create or implement FizzBuzz game program in java (with example)

What is Fizz buzz game?

Fig 1: Fizz, Buzz or FizzBuzz game

Approach 1: Using Java Stream

Implement FizzBuzz game using Java Stream

import java.util.function.IntPredicate;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class FizzBuzz {
    public static void main(String[] args) {
        final int LIMIT = 15;

        IntPredicate isDivisibleBy3 = i -> i % 3 == 0;
        IntPredicate isDivisibleBy5 = i -> i % 5 == 0;

        String result = IntStream.rangeClosed(1, LIMIT)
                .mapToObj(i -> {
                    String output = "";
                    if (isDivisibleBy3.test(i)) output += "Fizz";
                    if (isDivisibleBy5.test(i)) output += "Buzz";
                    return output.isEmpty() ? String.valueOf(i) : output;
                })
                .collect(Collectors.joining("\n"));

        System.out.println(result);
    }
}

Output: Program to print FizzBuzz game sequence.

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

Approach 2: Implement FizzBuzz – Traditional Loop

Program: Create FizzBuzz game in java (example)

package org.learn.fizzbuzz;

import java.util.Scanner;

public class DemoFizzBuzz {

	private static final String FIZZ = "Fizz";
	private static final String BUZZ = "Buzz";
	private static final String FIZZ_BUZZ = "FizzBuzz";

	public static void main(String[] args) {

		try (Scanner scanner = new Scanner(System.in)) {

			System.out.println("Enter input number : ");
			int inputNumber = scanner.nextInt();
			for (int number = 1; number <= inputNumber; number++) {

				// If number is divisible by 15 ( 5 * 3)
				if (number % 15 == 0) {
					System.out.printf("%s ", FIZZ_BUZZ);
				} else if (number % 3 == 0) { // If number is divisible by 3
					System.out.printf("%s ", FIZZ);
				} else if (number % 5 == 0) { // If number is divisible by 5
					System.out.printf("%s ", BUZZ);
				} else {
					System.out.printf("%d ", number);
				}
			}
		}
	}
}

Output: implement FizzBuzz game program in java:

Enter input number : 10
1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 

Enter input number : 18
1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz 16 17 Fizz 
Exit mobile version