Real Calculator In Java Programming By Using do_while loop and switch case

Calculator In Java Programming

Calculator In Java Programming which performs the basic four mathematical operations i.e., addition, subtraction, multiplication, and division, use the switch case to identify the input operator to perform required calculation and also used do while loop for continue the process and display the result on the screen as shown in the following program.

package calculator;
import java.util.Scanner;
public class Calculator {
static String op;
public double add(double a,double b){
a=(double) a+b;
System.out.println("result "+a);
return a;
}
public double multiply(double a,double b) {
a=a*b;
System.out.println("result "+a);
return a;
}
public double devision(double a,double b) {
a=a/b;
System.out.println("result "+a);
return a;
}
public double subtraction(double a,double b) {
a=a-b;
System.out.println("result "+a);
return a;
}
public static void main(String[] args) {
try{
Calculator c=new Calculator();
String quit="q";
Scanner s=new Scanner(System.in);
System.out.println("enter number");
double x=s.nextDouble();
String qui;
do{
System.out.println("enter oprator (q for quit and = to find the last result)");

String op=s.next();

//basic four mathematical operations i.e., addition, subtraction, multiplication, and division, use the switch case to identify the input operator to perform required calculation

switch(op){
case "+":
System.out.println("enter number");
double y=s.nextDouble();
x=c.add(x, y);
break;
case "-":System.out.println("enter number");
double minus=s.nextDouble();
x= c.subtraction(x, minus);
break;
case "*":
System.out.println("enter number");
double multi=s.nextDouble();
x= c.multiply(x, multi);break;
case "/":
System.out.println("enter number");
double division=s.nextDouble();
x= c.devision(x, division);
break;
case "=":
System.out.println("result "+x);
System.exit(0);break;
case "q":
System.exit(0) ;
}
}
while(op!=quit);
}
catch(Exception e)
{
System.out.println("Invalid Input");}
}
}

Output is:

run:
enter number
12
enter oprator (q for quit and = to find the last result)
+
enter number
36
result 48.0
enter oprator (q for quit and = to find the last result)
-
enter number
78
result -30.0
enter oprator (q for quit and = to find the last result)
/
enter number
25
result -1.2
enter oprator (q for quit and = to find the last result)
+
enter number
23
result 21.8
enter oprator (q for quit and = to find the last result)
q
BUILD SUCCESSFUL (total time: 48 seconds)

Add a Comment

Your email address will not be published. Required fields are marked *