Basic Java | Example of if - else in Java | Problem Solving in Java | Ask The Code
Problem:
The FizzBuzz Game Let's play a game of FizzBuzz! It works just like the popular childhood game "PopCorn", but with rules of math applied since math is fun, right? Just print out "Fizz" when the given number is divisible by 3, "Buzz" when it's divisible by 5, and "FizzBuzz" when it's divisible by both 3 and 5!
Let the game begin!
Instructions:
1. Scan a positive integer n and store it in a variable.
2. Create a counter variable with a value of 1 and create a loop from counter to n.
3. Print "Fizz" if the counter in the loop is divisible by 3, "Buzz" if the counter is divisible by 5, "FizzBuzz" if it is both divisible by 3 and 5.
4. Skip the iteration if it is not divisible by 3 or by 5.
Input Sample:
15
Output Sample:
Fizz
Buzz
Fizz
Fizz
Buzz
Fizz
FizzBuzz
Code:
import java.util.Scanner;
public class solution_FizzBuzz{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for (int count = 1; count <= n; count++) {
if (count % 3 == 0 && count % 5 == 0) {
System.out.println("FizzBuzz");
}
else if (count % 3 == 0) {
System.out.println("Fizz");
}
else if (count % 5 == 0) {
System.out.println("Buzz");
}
}
}
}
Comments