Basic Calculator in Java Using Switch - The Coding Shala

Home >> Java Programs >> Basic Calculator in Java

 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..


Other Posts You May Like
Please leave a comment below if you like this post or found some errors, it will help me to improve my content.

Comments

Popular Posts from this Blog

Shell Script to find sum, product and average of given numbers - The Coding Shala

New Year Chaos Solution - The Coding Shala

Shell Script to Create a Simple Calculator - The Coding Shala

Java Method Overloading - The Coding Shala

Java Program to Convert Binary to Decimal - The Coding Shala