Programming Examples
Java program to create arithmetic calculator
Write a Menu drive program to choose Arithmetic Operation and perform operation based on user choice:
Â
Solution
import java.util.Scanner;
public class CalculatorWithSwitch
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter first number: ");
double num1 = sc.nextDouble();
System.out.print("Enter second number: ");
double num2 = sc.nextDouble();
System.out.println("Choose an operation:");
System.out.println("1. Addition (+)");
System.out.println("2. Subtraction (-)");
System.out.println("3. Multiplication (*)");
System.out.println("4. Division (/)");
System.out.print("Enter your choice (1/2/3/4): ");
int choice = sc.nextInt();
double result = 0;
switch (choice)
{
case 1:
result = num1 + num2;
System.out.println("Result of addition: " + result);
break;
case 2:
result = num1 - num2;
System.out.println("Result of subtraction: " + result);
break;
case 3:
result = num1 * num2;
System.out.println("Result of multiplication: " + result);
break;
case 4:
if (num2 != 0) {
result = num1 / num2;
System.out.println("Result of division: " + result);
} else {
System.out.println("Error: Division by zero");
}
break;
default:
System.out.println("Invalid choice. Please enter a valid operation.");
break;
}
}
}
Output
Enter first number: 10
Enter second number: 5
Choose an operation:
1. Addition (+)
2. Subtraction (-)
3. Multiplication (*)
4. Division (/)
Enter your choice (1/2/3/4): 1
Result of addition: 15.0