Algorithm
-
Initialization:
- Declare variables for operand1, operand2, result, and operator.
- Prompt the user to enter operand1 and operand2.
- Prompt the user to choose an operation (+, -, *, /).
-
Input:
- Read operand1, operand2, and operator from the user.
-
Switch...case structure:
- Use a switch statement to perform different operations based on the chosen operator.
- Cases should include addition (+), subtraction (-), multiplication (*), and division (/).
-
Perform Calculation:
- Inside each case, perform the corresponding mathematical operation on operand1 and operand2.
- Handle division by zero if the operator is '/'.
-
Display Result:
- Print the result of the calculation.
-
Default Case:
- Handle the default case if the user enters an invalid operator.
Code Examples
#1 Code Example- Simple Calculator using Java switch Statement
Code -
Java Programming
import java.util.Scanner;
class Main {
public static void main(String[] args) {
char operator;
Double number1, number2, result;
// create an object of Scanner class
Scanner input = new Scanner(System.in);
// ask users to enter operator
System.out.println("Choose an operator: +, -, *, or /");
operator = input.next().charAt(0);
// ask users to enter numbers
System.out.println("Enter first number");
number1 = input.nextDouble();
System.out.println("Enter second number");
number2 = input.nextDouble();
switch (operator) {
// performs addition between numbers
case '+':
result = number1 + number2;
System.out.println(number1 + " + " + number2 + " = " + result);
break;
// performs subtraction between numbers
case '-':
result = number1 - number2;
System.out.println(number1 + " - " + number2 + " = " + result);
break;
// performs multiplication between numbers
case '*':
result = number1 * number2;
System.out.println(number1 + " * " + number2 + " = " + result);
break;
// performs division between numbers
case '/':
result = number1 / number2;
System.out.println(number1 + " / " + number2 + " = " + result);
break;
default:
System.out.println("Invalid operator!");
break;
}
input.close();
}
}
Copy The Code &
Try With Live Editor
Output
*
Enter first number
3
Enter second number
9
3.0 * 9.0 = 27.
#2 Code Example with Java Programming
Code -
Java Programming
result = number1 * number2;
System.out.println(number + " * " + number2 + " = " + result);
break;
Copy The Code &
Try With Live Editor
Output
+
Enter first number
21
Enter second number
8
21.0 + 8.0 = 29.0
#3 Code Example with Java Programming
Code -
Java Programming
start coding...
Copy The Code &
Try With Live Editor
Output
-
Enter first number
9
Enter second number
3
9.0 - 3.0 = 6.0
#4 Code Example with Java Programming
Code -
Java Programming
start coding...
Copy The Code &
Try With Live Editor
Output
/
Enter first number
24
Enter second number
8
24.0 / 8.0 = 3.0
Demonstration
Java Programing Example to Make a Simple Calculator Using switch...case-DevsEnv