Basic Calculator in Java Using Switch - The Coding Shala
Home >> Java Programs >> Basic Calculator in Java
Other Posts You May Like
In this post, we will be learning how to write Basic Calculator Program in Java using Switch statement.
Basic Calculator Program in Java Using Switch
We are writing a simple calculator program that will perform addition, subtraction, multiplication, and division based on given user inputs.
Example 1:
Input:
num1: 55
num2: 5
operator: +
Output: 55 + 5 = 60
Java Program:
/** * https://www.thecodingshala.com/ */ import java.util.*; public class Main { public static void main(String[] args) { System.out.println("Calculator program started.."); Scanner sc = new Scanner(System.in); boolean check = true; while (check) { System.out.println("Enter first number"); double num1 = sc.nextDouble(); System.out.println("Enter second number"); double num2 = sc.nextDouble(); System.out.println("Enter operator from -> +, -, *, /"); char op = sc.next().charAt(0); switch (op) { case '+': System.out.println(num1 + " + " + num2 + " = " + (num1 + num2)); break; case '-': System.out.println(num1 + " - " + num2 + " = " + (num1 - num2)); break; case '*': System.out.println(num1 + " * " + num2 + " = " + (num1 * num2)); break; case '/': if (num2 == 0) { System.out.println("Can't divide by 0"); } else { System.out.println(num1 + " / " + num2 + " = " + (num1 / num2)); } break; default: System.out.println("Please enter correct inputs"); } System.out.println("Do you want to continue?: y/n"); char flag = sc.next().charAt(0); if (flag == 'n') { check = false; } } System.out.println("Calculator program ended.."); } }
Output:
Calculator program started.. Enter first number 55 Enter second number 5 Enter operator from -> +, -, *, / + 55.0 + 5.0 = 60.0 Do you want to continue?: y/n n Calculator program ended..
- Java Program to find Sum of Digits of a Number
- Java Program to find Average of N number
- Java Program to find Sum of N Numbers
- Java Program to check if the given year is leap or not
- Java Program to Reverse an Array
Comments
Post a Comment