5. FizzBuzz 2.0
by CodeChum Admin
Remember the game of FizzBuzz from the last time? Well, I thought of some changes in the game, and also with the help of loops as well. Firstly, you'll be asking for a random integer and then loop from 1 until that integer. Then, implement these conditions in the game:
print "Fizz" if the number is divisible by 3
print "Buzz" if the number is divisible by 5
print "FizzBuzz" if the number is divisible by both 3 and 5
print the number itself if none of the above conditions are met
Input
A line containing an integer.
15
Output
Multiple lines containing a string or an integer.
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
SOLUTION TO THE ABOVE QUESTION
SOLUTION CODE
package com.company;
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("\nEnter a random integer: ");
int my_integer = sc.nextInt();
//use while loop to reach the number entered by the user
int terminate_condition = 0;
while (terminate_condition<=my_integer)
{
//if you reach your integer now check the conditions of the game
if(terminate_condition==my_integer)
{
if(my_integer%3==0 && my_integer%5==0)
{
System.out.println("\nFizzBuzz");
}
else if(my_integer%3==0)
{
System.out.println("\nFizz");
}
else if(my_integer%5==0)
{
System.out.println("\nBuzz");
}
else
{
System.out.println("\n"+my_integer);
}
}
terminate_condition = terminate_condition + 1;
}
}
}
SAMPLE PROGRAM OUTPUT
Comments
Leave a comment