FizzBuzz program in java

FizzBuzz Java

In this post, we will see how to program FizzBuzz in java.

Fizzbuzz is a fun game played generally by school children. It is simple game in which when your turn comes, you need to say the next number. So here are rules of the game:

  • If number is divisible by 3, then you need to say Fizz
  • If number is divisible by 5, then you need to say Buzz
  • If number is divisible by 3 and 5 both, then you need to say FizzBuzz
  • Else you just need to say next number

For example:

If there are 20 children then number will be printed as below:

1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz 16 17 Fizz 19 Buzz

Simple FizzBuzz Java solution

Here is simple FizzBuzz java solution

package org.arpit.java2blog;

import java.util.Scanner;

public class FizzBuzzMain {

    public static void main(String[] args) {

        Scanner s = new Scanner(System.in);
        System.out.println("Enter number:");
        int n = s.nextInt();
        System.out.println("The FizzBuzz numberswill be: ");
        for (int i = 1; i <= n; i++) {
            if (i % 3 == 0 && i % 5 == 0) { //multiple of 3 & 5
                System.out.print("FizzBuzz");
            } else if (i % 3 == 0) { //multiple of 3
                System.out.print("Fizz");
            } else if (i % 5 == 0) { //multiple of 5
                System.out.print("Buzz");
            } else {
                System.out.print(i);
            }
            System.out.print(" ");
        }
        s.close();
    }
}

Output of above program will be:

Enter number:
20
The FizzBuzz numbers will be:
1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz 16 17 Fizz 19 Buzz

Java FizzBuzz program using Java 8

Here is the one line solution for Java 8 using Java 8 Stream

IntStream.rangeClosed(1, n)
        .mapToObj(i -> i % 3 == 0 ? (i % 5 == 0 ? "FizzBuzz " : "Fizz ") : (i % 5 == 0 ? "Buzz " : i+" "))
        .forEach(System.out::print);

Complete java FizzBuzz program

package org.arpit.java2blog;

import java.util.Scanner;
import java.util.stream.IntStream;

public class FizzBuzzMain {

    public static void main(String[] args) {

        Scanner s = new Scanner(System.in);
        System.out.println("Enter number:");
        int n = s.nextInt();
        IntStream.rangeClosed(1, n)
        .mapToObj(i -> i % 3 == 0 ? (i % 5 == 0 ? "FizzBuzz " : "Fizz ") : (i % 5 == 0 ? "Buzz " : i+" "))
        .forEach(System.out::print);
        s.close();
    }
}

When you run above program, you will get below output:

Enter number:
15
1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz

That’s all about FizzBuzz program in java.

[social_share share_on="facebook,twitter,linkedin,whatsapp"][post_navigator in_same_term="true"]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.