In: Computer Science
Goals Practice conditional statements Description Write a program to simulate a menu driven calculator that performs basic arithmetic operations (add, subtract, multiply and divide). The calculator accepts two numbers and an operator from user in a given format: For example: Input: 6.3 / 3 Output: 2.1 Create a Calculator class that has a method to choose the right mathematical operation based on the entered operator using switch case. It should then call a corresponding method to perform the operation. In the main method of the testing class create an object of Calculator and accept user’s input using Scanner object, In java .
input code:
output:
code:
import java.util.*;
/*make a class */
class Calculator
{
/*declre the data memberss*/
double num1,num2;
/*parameterise constructor*/
Calculator(double n1,double n2)
{
num1=n1;
num2=n2;
}
/*Addition the numbers*/
double Addition()
{
return num1+num2;
}
/*substraction the number*/
double Substraction()
{
return num1-num2;
}
/*Multipication the numbers*/
double Multipication()
{
return num1*num2;
}
/*divide the numbers*/
double divide()
{
return num1/num2;
}
}
public class Main
{
public static void main(String[] args)
{
/*make object of Scanner*/
Scanner sc=new Scanner(System.in);
System.out.print("Addition(+)\nSubstraction(-)\nMultipication(*)\nDivide(/)\nEnter
the input: ");
/*take user input*/
double a=sc.nextDouble();
char op=sc.next().charAt(0);
double b=sc.nextDouble();
/*make object of Calculator
class*/
Calculator c=new
Calculator(a,b);
/*make switch*/
switch(op)
{
case '+': /*call Addition
function*/
System.out.print(a+" + "+b+" =
"+c.Addition());
break;
case '-': /*call Substraction
function*/
System.out.print(a+" - "+b+" =
"+c.Substraction());
break;
case '*': /*call Multipication
function*/
System.out.print(a+" * "+b+" =
"+c.Multipication());
break;
case '/': /*call divide
function*/
System.out.print(a+" / "+b+" =
"+c.divide());
break;
}
}
}