How I Solved the FizzBuzz Problem with a Switch Case in Java
Solve the classic FizzBuzz problem using a switch case in Java. The FizzBuzz problem is a common coding challenge that asks you to print numbers from 1 to a given number, but for multiples of 3, print "Fizz" instead of the number, for multiples of 5, print "Buzz," and for numbers which are multiples of both 3 and 5, print "FizzBuzz.
Hey everyone! Today, I want to share how I solved the classic FizzBuzz problem using a switch case in Java. The FizzBuzz problem is a common coding challenge that asks you to print numbers from 1 to a given number, but for multiples of 3, print "Fizz" instead of the number, for multiples of 5, print "Buzz," and for numbers which are multiples of both 3 and 5, print "FizzBuzz." Let's dive into how I tackled this using a switch case.
The Code
Here is the complete code for solving the FizzBuzz problem using a switch case:
import java.util.Scanner;
public class FizzBuzzSwitch {
public static void main(String[] args) {
int number;
String result = "";
@SuppressWarnings("resource")
Scanner input = new Scanner(System.in);
System.out.print("Hey! Enter a number: ");
number = input.nextInt();
boolean divisibleBy5 = number % 5 == 0;
boolean divisibleBy3 = number % 3 == 0;
int switchCase = (divisibleBy3 ? 1 : 0) + (divisibleBy5 ? 2 : 0);
switch (switchCase) {
case 1:
result = "Fizz";
break;
case 2:
result = "Buzz";
break;
case 3:
result = "FizzBuzz";
break;
default:
result = String.valueOf(number);
break;
}
System.out.println(result);
}
}
Breaking Down the Code
Let me break down the code step-by-step to explain how it works.
Setting Up the Variables
int number;
String result = "";
number
will store the input number that we will get from the user.result
will store the final result, which we will print out at the end.
Getting User Input
@SuppressWarnings("resource")
Scanner input = new Scanner(System.in);
System.out.print("Hey! Enter a number: ");
number = input.nextInt();
- We use a
Scanner
object to get user input from the console. @SuppressWarnings("resource")
is an annotation that suppresses the warning that theScanner
object is not closed. In a small program like this, it's okay to leave it open.- We prompt the user to enter a number and read that number using
input.nextInt()
, which stores the value in thenumber
variable.
Checking Divisibility
boolean divisibleBy5 = number % 5 == 0;
boolean divisibleBy3 = number % 3 == 0;
- We use the modulo operator
%
to check if the number is divisible by 5 and 3. number % 5 == 0
evaluates totrue
if the number is divisible by 5, andfalse
otherwise.number % 3 == 0
evaluates totrue
if the number is divisible by 3, andfalse
otherwise.- We store these boolean results in the variables
divisibleBy5
anddivisibleBy3
.
Calculating the Switch Case Value
int switchCase = (divisibleBy3 ? 1 : 0) + (divisibleBy5 ? 2 : 0);
- We use the ternary operator
? :
to determine the values based on the boolean variablesdivisibleBy3
anddivisibleBy5
. (divisibleBy3 ? 1 : 0)
evaluates to 1 ifdivisibleBy3
istrue
and 0 iffalse
.(divisibleBy5 ? 2 : 0)
evaluates to 2 ifdivisibleBy5
istrue
and 0 iffalse
.
By adding these two values, switchCase
can be 0, 1, 2, or 3, which represents the following cases:
- 0: The number is not divisible by 3 or 5.
- 1: The number is divisible by 3 but not by 5.
- 2: The number is divisible by 5 but not by 3.
- 3: The number is divisible by both 3 and 5.
Using the Switch Case
switch (switchCase) {
case 1:
result = "Fizz";
break;
case 2:
result = "Buzz";
break;
case 3:
result = "FizzBuzz";
break;
default:
result = String.valueOf(number);
break;
}
We use a switch case statement to determine the output based on the value of switchCase
.
case 1:
means the number is divisible by 3, so we setresult
to "Fizz".case 2:
means the number is divisible by 5, so we setresult
to "Buzz".case 3:
means the number is divisible by both 3 and 5, so we setresult
to "FizzBuzz".default:
handles the case where the number is not divisible by 3 or 5, so we setresult
to the number itself as a string usingString.valueOf(number)
.
Printing the Result
System.out.println(result);
Finally, we print the result
to the console.
So, using a switch case to solve the FizzBuzz problem in Java is an efficient and clean approach. It allows us to handle different cases of divisibility in a straightforward manner. This method ensures that the FizzBuzz logic is easy to understand and maintain. Give it a try and see how it works for you! Happy coding!
Related Tags
Recommended
2m · 4min read
Programming Languages
2m · 4min read
How I Solved the FizzBuzz Problem with a Switch Case in Java
Solve the classic FizzBuzz problem using a switch case in Java. The FizzBuzz problem is a common coding challenge that asks you to print numbers from 1 to a given number, but for multiples of 3, print "Fizz" instead of the number, for multiples of 5, print "Buzz," and for numbers which are multiples of both 3 and 5, print "FizzBuzz.
6m · 13min read
Programming Languages
6m · 13min read
When should I use JavaScript, C++, Java, or Python?
C++, Java, and Python are three of the most widely used programming languages, each with its own set of strengths and applications. C++: System programming, game development, Java: Enterprise applications, Android app development, Python: Data science, machine learning, scripting, rapid prototyping.
6m · 19min read
Programming Languages
6m · 19min read
TypeScript vs JavaScript: What are the Differences?
JavaScript and TypeScript are crucial in modern web development. While JavaScript is the foundation of web development, TypeScript offers additional features and benefits that can enhance the development experience and improve code quality.
6m · 7min read
Programming Languages
6m · 7min read
20 Programming Mistakes to Avoid as a Beginner
Avoiding common beginner programming mistakes is crucial for accelerating learning and becoming a proficient programmer. Including learning too many programming languages, frameworks, and technologies simultaneously
6m · 4min read
Programming Languages
6m · 4min read
What is the Difference Between Coding and Programming?
The terms "coding" and "programming" are often used interchangeably, but they represent distinct concepts within the realm of software development. Understanding the difference between these two terms is crucial for anyone interested in the field, as it helps clarify the roles, responsibilities, and skills required in software development.
6m · 4min read
Programming Languages
6m · 4min read
Understanding Threading and Multiprocessing in Python
Threading and multiprocessing are fundamental concepts in Python that enable concurrent execution of tasks, significantly improving the speed and efficiency of programs by allowing multiple operations to run simultaneously.
9m · 4min read
Programming Languages
9m · 4min read
JavaScript Basics for Web Development
JavaScript is a high-level interpreted programming language that is used for building interactive aspects in websites, expanding functionality. It's known for enhancing the user-friendliness of websites and adding cutting-edge interactive features.
9m · 6min read
Programming Languages
9m · 6min read
Understanding Variables in C++: From Declaration to Initialization
In C++, a variable is essentially a name given to a memory location. It is the basic unit of storage in a program. The value stored in a variable can be changed during program execution. All operations performed on a variable affect the memory location it refers to
9m · 3min read
Programming Languages
9m · 3min read
Most Popular Programming Languages in 2024
Explore the most popular programming languages in 2024. Discover the strengths, uses, and future prospects of Python, JavaScript, Java, C, PHP, and more. Stay ahead in the ever-evolving world of programming