Building a simple calculator in Java is an excellent practice project for beginners. It blends user input, control flow, arithmetic operations, and clear program structure. Here’s a step-by-step explanation of how to create a console-based calculator in Java.
What Will This Calculator Do?
Accept two numbers from the user.
Take an arithmetic operator (+, -, *, /) from the user.
Perform the chosen operation and show the result.
Handle invalid operations and errors (such as division by zero).
Step 1: Import Scanner for User Input
The Scanner
class allows your program to get input from the keyboard.
java
import java.util.Scanner;
Step 2: Main Program Structure
We’ll put all code inside the main method, which is the entry point for every Java application.
java
public class Calculator {
public static void main(String[] args) {
// Program code goes here
}
}
Step 3: Create Scanner and Prompt the User
You need to create a Scanner
object and use it to accept numbers and an operator:
java
Scanner scanner = new Scanner(System.in);
System.out.print("Enter first number: ");
double num1 = scanner.nextDouble();
System.out.print("Enter operator (+, -, *, /): ");
char operator = scanner.next().charAt(0);
System.out.print("Enter second number: ");
double num2 = scanner.nextDouble();
Step 4: Calculate the Result Using Control Flow
We’ll use a switch
statement to decide the operation based on the chosen operator:
java
double result;
switch (operator) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
if (num2 != 0) {
result = num1 / num2;
} else {
System.out.println("Error: Division by zero is not allowed.");
scanner.close();
return;
}
break;
default:
System.out.println("Invalid operator!");
scanner.close();
return;
}
Explanation:
- For each operation, the calculator computes and saves the result.
- It checks for division by zero to prevent a crash.
- If the operator is not recognized, it shows an error and exits.
Step 5: Display the Result
Finally, print the result:
java
System.out.println("Result: " + result);
scanner.close();
Complete Code: Simple Console-Based Calculator in Java
java
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter first number: ");
double num1 = scanner.nextDouble();
System.out.print("Enter operator (+, -, *, /): ");
char operator = scanner.next().charAt(0);
System.out.print("Enter second number: ");
double num2 = scanner.nextDouble();
double result;
switch (operator) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
if (num2 != 0) {
result = num1 / num2;
} else {
System.out.println("Error: Division by zero not allowed.");
scanner.close();
return;
}
break;
default:
System.out.println("Invalid operator!");
scanner.close();
return;
}
System.out.println("Result: " + result);
scanner.close();
}
}
Key Concepts Practiced in This Project
- User Input: Using Scanner to accept different types of data.
- Variables and Data Types: Storing numbers as double for arithmetic.
- Control Flow: Applying switch and if-else for decisions and validation.
- Error Handling: Catching invalid operators and division by zero.
- Output: Displaying results to the user.
How to Run the Calculator
1.Copy the complete code into a file named Calculator.java
.
2. Compile:
Open a terminal in the file’s folder and run:
text
javac Calculator.java
3. Run:
text
java Calculator
Enter numbers and operators as prompted to perform calculations!
Tips to Expand
- Add more operations (e.g., modulus %, power **).
- Allow calculations in a loop until the user wants to exit.
- Handle invalid input (such as letters instead of numbers) with exception handling.
Final Thoughts
Building small projects like this calculator gives you practical confidence in Java basics and forms a foundation for bigger, real-world applications. Happy coding!
Check out the YouTube Playlist for great java developer content for basic to advanced topics.
Please Do Subscribe Our YouTube Channel for clearing programming concept and much more ... : CodenCloud
Top comments (0)