This Java program simply creates an option to chose the Operators just like any calculator. A switch statement is used for creating an option in programming that will make case for a different option and operate according to the option that the user provides. It will also take two operands (numbers) at the beginning.
If you do not know about the Switch Case statement or Data Types in java, click the link below to learn about them as this program uses one.
Java Program to make a Calculator using a Switch Statement
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | //Making Calculator using a switch in Java import java.util.Scanner; public class CalculatorJava { public static void main(String[] args) { double result; char operator; Scanner reader = new Scanner(System.in); System.out.print("Enter first numbers: "); double num1 = reader.nextDouble(); System.out.print("Enter second numbers: "); double num2 = reader.nextDouble(); System.out.print("Choose an operator(+, -, *, /): "); operator=reader.next().charAt(0); //switch case switch (operator) { case '+': result = num1 + num2; break; case '-': result = num1 - num2; break; case '*': result = num1 * num2; break; case '/': result = num1 / num2; break; default: System.out.printf("Error! operator is not correct"); return; } //Displaying result System.out.printf("%.1f %c %.1f = %.1f", num1, operator, num2, result); } } |
Output:
Enter first numbers: 5
Enter second numbers: 3
Choose an operator (+, -, *, /): -
5.0 - 3.0 = 2.0