Build a Simple Calculator Using Switch Statements in Java
Creating a calculator is one of the best ways to start learning programming. In this article, we will create a simple calculator in Java using switch statements. This calculator will perform basic arithmetic operations like addition, subtraction, multiplication, and division based on user input.
📌 What is a Switch Statement in Java?
A switch statement in Java is used to perform different actions based on different conditions. It works like an if-else-if ladder but makes the code cleaner and more readable when you have multiple conditions to check.
🛠️ Features of Our Calculator:
-
Takes two numbers as input from the user.
-
Takes an operator as input (
+
,-
,*
,/
). -
Google Advertisement
Performs the chosen operation using a switch statement.
-
Displays the result to the user.
✅ Java Code for Simple Calculator Using Switch
🧠 Step-by-Step Explanation of the Code
🔹 Step 1: Import Scanner for User Input
We import Scanner
class from the Java utility package so that we can take input from the user.
🔹 Step 2: Get the Numbers
We ask the user to enter two numbers. These are stored as double
to allow decimal values.
🔹 Step 3: Get the Operator
We ask the user to enter an operator like +
, -
, *
, or /
. We read the first character of the input using .charAt(0)
.
🔹 Step 4: Use Switch Statement
The switch checks the value of operator
and runs the matching case block.
🔹 Step 5: Perform Operation & Display Result
For each case, we perform the calculation and print the result. If the operator is invalid, the default
case handles it with a message.
❗ Important Notes:
-
Always check for division by zero to avoid errors.
-
switch
is case-sensitive, so only valid symbols will work. -
Use
scanner.close()
at the end to prevent resource leaks.
🎯 Conclusion
You’ve now learned how to create a basic calculator in Java using switch statements. This is a great beginner project to understand user input, control statements, and basic arithmetic operations.
Once you’re comfortable with this, try expanding the calculator by:
-
Adding more operations like modulus (
%
) -
Supporting multiple calculations in a loop
-
Handling invalid input more gracefully