This document presents a simple calculator program written in Java that can perform basic arithmetic operations: addition, subtraction, multiplication, and division. The objective of this program is to provide a user-friendly interface for performing these operations via the command line.
Calculator Code
import java.util.Scanner;
public class SimpleCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Welcome to the Simple Calculator!");
while (true) {
System.out.println("Please enter the first number (or 'exit' to quit):");
String input1 = scanner.nextLine();
if (input1.equalsIgnoreCase("exit")) {
break;
}
double num1 = Double.parseDouble(input1);
System.out.println("Please enter the second number:");
double num2 = Double.parseDouble(scanner.nextLine());
System.out.println("Choose an operation: +, -, *, /");
char operation = scanner.nextLine().charAt(0);
double result;
switch (operation) {
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.");
continue;
}
break;
default:
System.out.println("Invalid operation. Please try again.");
continue;
}
System.out.printf("The result of %.2f %c %.2f = %.2f%n", num1, operation, num2, result);
}
System.out.println("Thank you for using the Simple Calculator. Goodbye!");
scanner.close();
}
}
Program Structure and How to Run the Program
The Simple Calculator program consists of the following components:
- Imports: The program imports the
java.util.Scannerclass to handle user input. - Main Method: The execution begins in the
mainmethod, where user interaction takes place. - While Loop: The program runs in a loop until the user types ‘exit’. This allows multiple calculations without restarting the program.
- User Input: It prompts the user for two numbers and an operation, handling input using the
Scanner. - Switch Statement: This controls which arithmetic operation to perform based on user input.
- Error Handling: The program checks for division by zero and handles invalid operations gracefully.
Steps to Run the Program
- Ensure you have Java Development Kit (JDK) installed on your computer.
- Create a new file named
SimpleCalculator.javaand copy the provided code into it. - Open your command line interface (CLI) and navigate to the directory where you saved the file.
- Compile the program using the command:
javac SimpleCalculator.java - Run the compiled program with the command:
java SimpleCalculator - Follow the on-screen prompts to perform calculations.
