Table of Contents
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 sayFizz
- If number is divisible by
5
, then you need to sayBuzz
- If number is divisible by
3
and5
both, then you need to sayFizzBuzz
- 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
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
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
Read also: FizzBuzz implementation in Python
Java FizzBuzz program using Java 8
Here is the one line solution for Java 8 using Java 8 Stream
1 2 3 4 5 |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
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
15
1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz
That’s all about FizzBuzz program in java.
Was this post helpful?
Let us know if this post was helpful. Feedbacks are monitored on daily basis. Please do provide feedback as that\'s the only way to improve.