The FizzBuzz problem is a frequently asked question in technical interviews. In real life, it is a game which is played by a group of people. The rules are quite straightforward.
The sequence of turns is decided before starting the game.
The first player starts by saying any number (usually the number 1).
The next player says the next number, and so on. However, the following is the tricky part:
The rules to say these words can be changed. For example, saying FizzBuzz when a number is a multiple of both 7 and 9.
If you say the wrong number or word, you’re out! The last player standing wins the game.
In Java, this problem is not about playing the game. It is a matter of knowing how to use the if-else condition (or its alternatives) to print (output) the correct number or word. Below is the code using both if-else and the ‘?’ operator:
public class main {public static void main(String[] arg) {// Fizz = multiple of 5// Buzz = multiple of 7// FizzBuzz = multiple of bothfor(int i = 1; i < 100; i++) {if(i % 5 == 0 && i % 7 == 0)System.out.println("FizzBuzz");else if(i % 5 == 0)System.out.println("Fizz");else if(i % 7 == 0)System.out.println("Buzz");elseSystem.out.println(i);}}}
Free Resources