In this post, we will write a Java program to implement the FizzBuzz game.
FizzBuzz is a game that is popular among kids. By playing this, kids learn the division. Now, the FizzBuzz game has become a popular programming question that is frequently asked in Java programming interviews. In this section, we will learn how to create a FizzBuzz program in Java.
Problem
Problem: Consider you have given a positive number n.Write a Java program that prints the numbers from 1 to 100.
- For multiples of 3, print "fizz"
- For multiples of 5, print "buzz"
- For multiples of 3 and 5, print "fizzbuzz"
Java FizzBuzz Program
public class FizzBuzz{
public static void main(String []args){
FizzBuzz.print(100);
}
public static void print(int n) {
for (int i = 1; i <= n; i++) {
if (((i % 5) == 0) && ((i % 7) == 0)) { // multiple of 5 & 7
System.out.println("fizzbuzz");
} else if ((i % 5) == 0) { // multiple of 5
System.out.println("fizz");
} else if ((i % 7) == 0) { // multiple of 7
System.out.println("buzz");
} else {
System.out.println(i); // not a multiple of 5 or 7
}
}
}
}
Output:
1 2 3 4 fizz 6 buzz 8 9 fizz 11 12 13 buzz fizz 16 17 18 19 fizz buzz 22 23 24 fizz 26 27 buzz 29 fizz 31 32 33 34 fizzbuzz 36 37 38 39 fizz 41 buzz 43 44 fizz 46 47 48 buzz fizz 51 52 53 54 fizz buzz 57 58 59 fizz 61 62 buzz 64 fizz 66 67 68 69 fizzbuzz 71 72 73 74 fizz 76 buzz 78 79 fizz 81 82 83 buzz fizz 86 87 88 89 fizz buzz 92 93 94 fizz 96 97 buzz 99 fizz