Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

fizzbuzz
problem
java

What is the FizzBuzz problem in Java?

Educative Answers Team

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Answers Code

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 Rules:

  • 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:

    1. Say the word Fizz instead of the number when it is a multiple of 3.
    2. Say Buzz if it is a multiple of 5.
    3. Say FizzBuzz if it is a multiple of both 3 and 5.
  • 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.

svg viewer
One round of FizzBuzz

Implementing FizzBuzz in Java

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 both
for(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");
else
System.out.println(i);
}
}
}
Using if-else

RELATED TAGS

fizzbuzz
problem
java
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Answers Code
Keep Exploring