Q. Java program to make a simple calculator using switch case.
Here you will find an algorithm and program in Java programming language to make a simple calculator. First let us understand what is calculator?
Explanation : A calculator is used to make mathematical calculations. In this program we will create a simple calculator that can perform an arithmetic operation (+, -, *, /).
Calculator Program Algorithm
START Step 1 : Initialise the two numbers. Step 2 : Ask the user to enter an option by giving six options. Step 3 : After getting the option from the user write if conditions for every operation based on the option. Step 4 : Perform the respective operation. Step 5 : Print the result. STOP
Java Program to Make a Simple Calculator
import java.util.Scanner; public class LFC { public static void main(String[] args) { Scanner reader = new Scanner(System.in); System.out.print("Enter two operands: "); // nextDouble() reads the next double from the keyboard double num1 = reader.nextDouble(); double num2 = reader.nextDouble(); System.out.print("Enter an operator (+, -, *, /): "); char ch = reader.next().charAt(0); double res; switch(ch) { case '+': res = num1 + num2; break; case '-': res = num1 - num2; break; case '*': res = num1 * num2; break; case '/': res = num1 / num2; break; // operator doesn't match any case constant (+, -, *, /) default: System.out.printf("Error! operator is not correct"); return; } System.out.printf("%.1f %c %.1f = %.1f", num1, ch, num2, res); } }
Output
Enter an operator (+, -, *, /): * Enter two operands: 8 6 8.0 * 6.0 = 48.0