Make calculator using Switch case

In this article we learn make the calculator by using switch .
A switch statement is a type of selection control mechanism used to allow the value of a variable or expression to change the control flow of program execution.
Example:-

//code

import java.util.Scanner;
class demo
{
public static void main(String arg[])
{
int x= 0, y=0;
Scanner sc=new Scanner(System.in);
System.out.println(“enter choice \n1.add \n2.sub \n3.mul \n4.div”);
int ch=sc.nextInt();
switch(ch)
{
case 1:
System.out.println(“enter two number”);
x=sc.nextInt();
y=sc.nextInt();
x=x+y;
System.out.println(“result is=”+x);
break;

case 2:
System.out.println(“enter two number”);
x=sc.nextInt();
y=sc.nextInt();
x=x-y;
System.out.println(“result is=”+x);
break;

case 3:
System.out.println(“enter two number”);
x=sc.nextInt();
y=sc.nextInt();
x=x*y;
System.out.println(“result is=”+x);
break;

case 4:
System.out.println(“enter two number”);
x=sc.nextInt();
y=sc.nextInt();
x=x/y;
System.out.println(“result is=”+x);
break;

default:
System.out.println(“invalid number”);
}
}
}

Step 1: Name it as “add.java”and save the file in any location i saved at “c:/kiran/program”.
Step 2: Set the paath,without path setting our java file is not compile.

1

Step 3: Set the path (path set means where you save your java file).

Step 4: Now write the following code for checking my java file is compiling or not.
javac add.java

3

My java program compiled successfully.

Step 5: Write the following code in command prompt. press enter and see the output.
java demo
// demo is a class name which is written in my “add.java” file.
Output

4

Step 6: Continue in output and see the full output.

5

I hope you like this article.
Happy codding.