Building a calculator is one of the most common beginner projects in programming. It helps you understand basic concepts like input handling, control flow, and user interaction. In this tutorial, we’ll create a simple console-based calculator in Java that can perform the four basic arithmetic operations: addition, subtraction, multiplication, and division.
Why Build a Calculator?
- It reinforces fundamental programming concepts.
- Helps you get comfortable with Java syntax and control structures.
- Introduces you to basic user input handling.
- You can later enhance it with a GUI or advanced features.
Step 1: Understand the Requirements
Our calculator should:
- Take two numbers as input from the user.
- Allow the user to select an operation (add, subtract, multiply, divide).
- Perform the operation and display the result.
- Handle invalid input gracefully (e.g., division by zero).
- Allow the user to perform multiple calculations until they choose to exit.
Step 2: Setup Java Environment
Make sure you have Java installed on your machine. You can write and compile this program using any IDE like IntelliJ IDEA, Eclipse, or even the command line.
Step 3: Writing the Calculator Code
Here’s the full Java code with detailed comments explaining each part.
import java.util.Scanner;
public class SimpleCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
boolean continueCalculation = true;
System.out.println("Welcome to Codex First Simple Calculator!");
while (continueCalculation) {
// Prompt user to enter the first number
System.out.print("Enter first number: ");
double num1 = getValidNumber(scanner);
// Prompt user to enter the second number
System.out.print("Enter second number: ");
double num2 = getValidNumber(scanner);
// Prompt user to choose an operation
System.out.println("Choose an operation:");
System.out.println("1 - Add (+)");
System.out.println("2 - Subtract (-)");
System.out.println("3 - Multiply (*)");
System.out.println("4 - Divide (/)");
int choice = getValidOperation(scanner);
// Perform the calculation based on user choice
double result = 0;
boolean validOperation = true;
switch (choice) {
case 1:
result = num1 + num2;
break;
case 2:
result = num1 - num2;
break;
case 3:
result = num1 * num2;
break;
case 4:
if (num2 == 0) {
System.out.println("Error: Division by zero is not allowed.");
validOperation = false;
} else {
result = num1 / num2;
}
break;
default:
System.out.println("Invalid operation choice.");
validOperation = false;
break;
}
// Display result if operation was valid
if (validOperation) {
System.out.printf("Result: %.2f\n", result);
}
// Ask user if they want to perform another calculation
System.out.print("Do you want to perform another calculation? (yes/no): ");
continueCalculation = scanner.next().equalsIgnoreCase("yes");
System.out.println();
}
System.out.println("Thank you for using Codex First Simple Calculator! Goodbye.");
scanner.close();
}
// Method to safely get a valid number from user input
private static double getValidNumber(Scanner scanner) {
while (!scanner.hasNextDouble()) {
System.out.println("Invalid input. Please enter a valid number:");
scanner.next(); // Discard invalid input
}
return scanner.nextDouble();
}
// Method to safely get a valid operation choice from user input
private static int getValidOperation(Scanner scanner) {
while (!scanner.hasNextInt()) {
System.out.println("Invalid input. Please enter a number between 1 and 4:");
scanner.next();
}
int operation = scanner.nextInt();
while (operation < 1 || operation > 4) {
System.out.println("Please choose a valid operation (1-4):");
while (!scanner.hasNextInt()) {
System.out.println("Invalid input. Please enter a number between 1 and 4:");
scanner.next();
}
operation = scanner.nextInt();
}
return operation;
}
}
Step 4: How This Code Works
Input Handling with Scanner
We use Scanner
to read input from the console. Because user input can be unpredictable, the methods getValidNumber
and getValidOperation
ensure that the input is valid before proceeding.
The Loop
The while (continueCalculation)
loop allows the user to perform multiple calculations without restarting the program. The user can exit by typing “no” when prompted.
Choosing Operations
The program displays a menu of operations (Add, Subtract, Multiply, Divide) and reads the user’s choice. A switch
statement performs the correct operation.
Division by Zero Handling
Division by zero is checked to prevent runtime errors. If the user tries to divide by zero, an error message is shown, and the calculation is skipped.
Step 5: Running the Program
Compile and run the program:
javac SimpleCalculator.java
java SimpleCalculator
You should see prompts to enter numbers and choose operations. Try entering invalid inputs to test the error handling.
Step 6: Next Steps
You can enhance this basic calculator by:
- Adding more operations (modulus, exponentiation).
- Implementing a GUI with Java Swing or JavaFX.
- Adding memory functions (store and recall values).
- Supporting operations on multiple numbers or continuous calculations.
Conclusion
Building this simple calculator is an excellent way to get hands-on experience with Java basics, input validation, and control structures. As you practice and build more features, you’ll gain confidence in Java programming.
Try modifying the code, adding new operations, or turning it into a graphical app — the possibilities are endless!