CS2- Assignment 2 OOP Calculator Weve all (probably) written a calculator progra
ID: 3885966 • Letter: C
Question
CS2- Assignment 2 OOP Calculator Weve all (probably) written a calculator program before, but now we will some object oriented programming principles. make one using Your program must: Use the following abstract classes and design pattern class to create a calculator o may not modify prototypes of the functionsbut additional You the existing , may add functionality to the classes within the spirit of the assignment if needed o The calculator must follow order of operations (modulus is on the same tier as multiplication/division), but does not need parenthesis • Each operator (plus, minus, multiplication, division, modulus) must be implemented as its own class, using polymorphism to give them different functions • You do not need to implement parenthesis, but you do need operator precedence I / This class represents an operator (eg. Plus, minus etc.) Using polymorphism, We can have a shared operate function as an interface so that we can use operator types interchangeably class Operator public: / Perform the operation on the two inputs virtual double operate(double input1, double input2 - O) = 0; }; / This represents what is on either side of an operator, you will likely need to make subclasses for numbers and expressions class operand public: I Return the value stored in this object virtual double getValue() = 8; class CalculatorFactory public: I/Input: character of an operator (eg. '+' for plus) /output: an object of the correct operator sub-class static Operator * createOperator(char symbol); I/Input: string of sub-expression i I/Output: object of correct operand sub-class (. .e, number vs expression) static Operand * createOperand(string input); I/Input: String of expression I/Output: Calculated value static double calculate(string input);Explanation / Answer
public class Calculator {
public Calculator(); {
}
public int add(int a, int b) {
return a + b;
}
public int subtract(int a, int b) {
return a - b;
}
public int multiply(int a, int b) {
return a * b;
}
public int divide(int a, int b) {
if (b == 0) {
System.out.println("Error! Dividing by zero is not allowed.");
return 0;
}
else {
return a / b;
}
}
public int modulo(int a, int b) {
if (b == 0) {
System.out.println("Error! Dividing by zero is not allowed.");
}
else {
return a % b;
}
}
public static void main(String[] args) {
Calculator myCalculator = new Calculator();
System.out.println(myCalculator.add(5,7));
System.out.println(myCalculator.subtract(45,11));
}
}