1. Introduction
In this tutorial, we will develop a simple calculator in Java that can perform basic arithmetic operations like addition, subtraction, multiplication, and division.
2. Program Steps
1. Define a class named SimpleCalculator.
2. In the main method of the class, use Scanner to take user input.
3. Display a menu to the user to select the operation.
4. Take the user’s choice and perform the corresponding operation.
5. Display the result of the operation.
3. Code Program
import java.util.Scanner; // Import Scanner class
public class SimpleCalculator { // Step 1: Define a class named SimpleCalculator
public static void main(String[] args) { // Main method
Scanner scanner = new Scanner(System.in); // Step 2: Use Scanner to take user input
System.out.println("Simple Calculator");
System.out.println("1. Add");
System.out.println("2. Subtract");
System.out.println("3. Multiply");
System.out.println("4. Divide");
System.out.print("Enter choice (1/2/3/4): "); // Step 3: Display a menu to the user
int choice = scanner.nextInt(); // Take user's choice
System.out.print("Enter first number: ");
double num1 = scanner.nextDouble();
System.out.print("Enter second number: ");
double num2 = scanner.nextDouble();
double result = 0;
// Step 4: Perform the corresponding operation
switch(choice) {
case 1:
result = num1 + num2;
break;
case 2:
result = num1 - num2;
break;
case 3:
result = num1 * num2;
break;
case 4:
result = num1 / num2;
break;
default:
System.out.println("Invalid choice");
break;
}
// Step 5: Display the result of the operation
System.out.println("Result: " + result);
scanner.close(); // Close the Scanner
}
}
Output:
Simple Calculator 1. Add 2. Subtract 3. Multiply 4. Divide Enter choice (1/2/3/4): 1 Enter first number: 5 Enter second number: 3 Result: 8.0
4. Step By Step Explanation
– Step 1: The SimpleCalculator class is defined.
– Step 2: A Scanner object is created to take user input.
– Step 3: A menu is displayed to the user, prompting them to select an operation.
– Step 4: Depending on the user's choice, the corresponding arithmetic operation is performed using a switch case.
– Step 5: The result of the operation is displayed to the user.