Ticker

6/recent/ticker-posts

Header Ads Widget

Calculator using switch statement

Calculator using switch statement Java





Introduction
In this tutorial we gonna make a calculator using switch statement in Java, very easy program which help user to perform four basic operation, multiply divide, subtract ,addition.



In this program firstly we will initialise two variable to store two values entered by user and then we print a message on screen for user to enter two number and then we scan that two numbers and show a small menu for the user to choose which operation he want to perform on these two number and then according to that using switch statement we will perform it.


In switch statement we will have 5 cases four the mathematical operation and one as default.

Q) write a Java program for calculator using switch statement.
Sol.)




import java.util.Scanner;

public class Calculator {

    public static void main(String[] args) {
double a,b;
        Scanner reader = new Scanner(System.in);
        System.out.print("Enter two numbers: ");

         a = reader.nextDouble();
        b = reader.nextDouble();

        System.out.print("Enter an operator (+, -, *, /): ");
        char operator = reader.next().charAt(0);

        double solution;

        switch(operator)
        {
            case '+':
                solution = a + b;
                 System.out.printf("solution =" + solution);
                break;

            case '-':
                solution = a - b;
                 System.out.printf("solution =" + solution);
                break;

            case '*':
                solution = a * b;
                 System.out.printf("solution =" + solution);
                break;

            case '/':solution=a/b;
             System.out.printf("solution =" + solution);
                break;

           
            default:
                System.out.printf("Error! operator is not correct");
                return;
        }
    }
}




Output:

Enter two numbers: 2
1
Enter an operator (+, -, *, /): +
solution =3.0
[Program finished]




Post a Comment

0 Comments