Simple Calculator Project in Java

Introduction

A simple calculator is a classic beginner project that demonstrates core programming concepts such as user input, conditional logic, arithmetic operations, and basic error handling. In Java, this project can be implemented using the console (command-line interface) with the Scanner class for input and if-else or switch statements for operation selection. This guide provides a complete, well-structured implementation of a calculator that supports addition, subtraction, multiplication, and division—with input validation and division-by-zero protection.


Features of the Calculator

  • Performs four basic operations: +, -, *, /
  • Accepts two numeric inputs from the user
  • Validates operator input
  • Handles division by zero gracefully
  • Uses a loop to allow multiple calculations
  • Clean, user-friendly prompts and output

Complete Source Code

import java.util.Scanner;
public class SimpleCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
char choice;
System.out.println("=== Simple Calculator ===");
do {
// Input first number
System.out.print("Enter first number: ");
while (!scanner.hasNextDouble()) {
System.out.println("Invalid input. Please enter a number.");
scanner.next(); // Clear invalid input
System.out.print("Enter first number: ");
}
double num1 = scanner.nextDouble();
// Input operator
System.out.print("Enter operator (+, -, *, /): ");
String opInput = scanner.next();
while (opInput.length() != 1 || !isValidOperator(opInput.charAt(0))) {
System.out.println("Invalid operator. Please use +, -, *, or /.");
System.out.print("Enter operator (+, -, *, /): ");
opInput = scanner.next();
}
char operator = opInput.charAt(0);
// Input second number
System.out.print("Enter second number: ");
while (!scanner.hasNextDouble()) {
System.out.println("Invalid input. Please enter a number.");
scanner.next();
System.out.print("Enter second number: ");
}
double num2 = scanner.nextDouble();
// Perform calculation
double result;
boolean validOperation = true;
switch (operator) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
if (num2 == 0) {
System.out.println("Error: Division by zero is not allowed.");
validOperation = false;
} else {
result = num1 / num2;
}
break;
default:
System.out.println("Unexpected error.");
validOperation = false;
result = 0;
}
// Display result
if (validOperation && operator != '/' || (operator == '/' && num2 != 0)) {
System.out.printf("%.2f %c %.2f = %.2f%n", num1, operator, num2, result);
}
// Ask to continue
System.out.print("\nDo you want to perform another calculation? (y/n): ");
choice = scanner.next().toLowerCase().charAt(0);
} while (choice == 'y');
System.out.println("Thank you for using the Simple Calculator!");
scanner.close();
}
// Helper method to validate operator
private static boolean isValidOperator(char op) {
return op == '+' || op == '-' || op == '*' || op == '/';
}
}

How It Works

1. Input Handling

  • Uses Scanner to read user input.
  • Validates that numbers are valid double values using hasNextDouble().
  • Clears invalid tokens with scanner.next() to prevent infinite loops.

2. Operator Validation

  • Ensures the operator is exactly one of: +, -, *, /.
  • Uses a helper method isValidOperator() for clean code.

3. Arithmetic Logic

  • Uses a switch statement for clear, efficient operation selection.
  • Checks for division by zero before performing /.

4. Output Formatting

  • Uses printf to display results with two decimal places for consistency.
  • Example: 5.00 + 3.00 = 8.00

5. Loop for Reusability

  • The do-while loop allows multiple calculations without restarting the program.
  • Prompts the user to continue after each operation.

Sample Output

=== Simple Calculator ===
Enter first number: 10
Enter operator (+, -, *, /): *
Enter second number: 4.5
10.00 * 4.50 = 45.00
Do you want to perform another calculation? (y/n): y
Enter first number: 7
Enter operator (+, -, *, /): /
Enter second number: 0
Error: Division by zero is not allowed.
Do you want to perform another calculation? (y/n): n
Thank you for using the Simple Calculator!

Key Concepts Demonstrated

ConceptImplementation in Code
User InputScanner class
Data ValidationhasNextDouble(), input loops
Conditional Logicswitch statement
Arithmetic Ops+, -, *, /
Error HandlingDivision-by-zero check
Loopsdo-while for repeated use
MethodsisValidOperator() helper
Formatted OutputSystem.out.printf()

Possible Enhancements

  • Add support for more operations (e.g., modulus %, exponentiation).
  • Implement memory functions (M+, M-, MR).
  • Create a GUI version using JavaFX or Swing.
  • Support expressions with parentheses (requires parsing).
  • Save calculation history to a file.

Conclusion

This simple calculator project encapsulates fundamental Java programming skills in a practical, functional application. It emphasizes robust input handling, clear user interaction, and defensive programming against common errors like invalid input and division by zero. The code is modular, readable, and extensible—making it an excellent foundation for beginners to build upon. By completing this project, learners gain confidence in controlling program flow, managing user input, and applying core language features to solve real-world problems.

Leave a Reply

Your email address will not be published. Required fields are marked *


Macro Nepal Helper