# Java program to build a calculator

In this java program, we are writing code for a simple calculator. Here, we are performing multiple basic mathematical tasks using switch case statement and do while loop.
Submitted by IncludeHelp, on November 19, 2017

Given numbers and we have to perform mathematical operations using java program.

Here, we have following operations to be performed through this program,

2. Subtraction
3. Division
4. Multiplication
5. Exit

Program will run infinite times until we do not press the 5 (a user choice).

## Program for simple mathematical operations (calculator) in java

```import java.util.Scanner;

public class Calculator
{
public static void main(String args[])
{
// declare here
float a,b,res;
char choice, ch;
Scanner S=new Scanner(System.in);

do
{
// prepare menu for the user to see multiple operations.

// enter the choice

// read the input choice value.
choice=S.next().charAt(0);

// this loop will calculate different the operations value at different dofferent values.
switch(choice)
{
case '1':System.out.print("Enter two numbers : ");
a=S.nextFloat();
b=S.nextFloat();
res=a+b;
System.out.print("Result : " +res);
break;

case '2':System.out.print("Enter two numbers : ");
a=S.nextFloat();
b=S.nextFloat();
res=a-b;
System.out.print("Result : " +res);
break;

case '3':System.out.print("Enter two numbers : ");
a=S.nextFloat();
b=S.nextFloat();
res=a/b;
System.out.print("Result : " +res);
break;

case '4':System.out.print("Enter two numbers : ");
a=S.nextFloat();
b=S.nextFloat();
res=a*b;
System.out.print("Result : " +res);
break;

case '5':
System.exit(0);
break;
default : System.out.print("Wrong Choice.....\n");
break;
}
}
// loop works till the number 5 not selected.
while(choice!=5);
}
}
```

Output

```Main Menu :
2.Subtraction
3.Division
4.Multiplication
5.Exit

Enter two numbers : 2 5
Result : 7.0

2.Subtraction
3.Division
4.Multiplication
5.Exit

Enter two numbers : 8 6
Result : 2.0

2.Subtraction
3.Division
4.Multiplication
5.Exit

Enter two numbers : 10 2
Result : 5.0

2.Subtraction
3.Division
4.Multiplication
5.Exit

Enter two numbers : 5 5
Result : 25.0

2.Subtraction
3.Division
4.Multiplication
5.Exit

```