Question: you will be implementing a text-based postfix calculator which takes input in postfix notation and displays the results of the computation. Write two classes OperationTest
you will be implementing a text-based postfix calculator which takes input in postfix notation and displays the results of the computation. Write two classes OperationTest and CalculatorMemoryTest that have JUnit tests that test all of the public methods of those two classes. Here are the classes. Fix any bigs you find. write JUnit test for these 2 classes
public class Operation {
public static int performOperation (char op, int left, int right) {
int result = 0;
if (op == '+')
result = left + right;
else if (op == '-')
result = right - left;
else if (op == '*')
result = left * right;
else if (op == '/') {
try {
result = left / right;
} catch (Exception e) {
System.out.println("Divide by Zero error ");
}
}
else
throw new IllegalArgumentException();
return result;
}
}
public class CalculatorMemory {
private int arr [];
private int top;
private int MAX = 1000;
public void CaculatorMemory () {
arr = new int [MAX];
top = - 1;
}
public void push (int number) throws Exception {
if (top == MAX - 1)
throw new Exception ("Stack Overflow");
top++;
arr[top] = number;
}
public int pop () throws Exception {
if (isEmpty())
throw new Exception ("Stack underflow");
int num = arr[top];
top--;
return num;
}
public boolean isEmpty () {
return top == -1;
}
public int size () {
return top + 1;
}
public void clear () {
top = -1;
}
public String toString() {
String str = "Memory contents: ";
for (int i = top; i >= 0; i--)
str+= arr[i] + " ";
str+= "--- ";
return str;
}
}
Here is also a method where calculator runs, you dont need to write JUnit tests but in case you want to test it in Eclipse.
package calculator;
import java.util.Scanner;
public class Calculator {
private CalculatorMemory calc;
private Scanner sc;
public Calculator() {
calc = new CalculatorMemory();
sc = new Scanner (System.in);
}
public void run () throws Exception {
String str;
System.out.println("Enter a number or operator: ");
str = sc.nextLine();
int number, left, right;
if (str.equals("+") || str.equals ("-") || str.equals("*") || str.equals("/")) {
right = calc.pop();
left = calc.pop();
number = Operation.performOperation(str.charAt(0), left, right);
calc.push(number);
} else {
try {
number = Integer.parseInt(str);
calc.push(number);
} catch (Exception E) {
System.out.println("Invalid input");
}
}
System.out.println(calc);
}
public static void main (String [] args) throws Exception {
Calculator calculator = new Calculator();
while (true) {
calculator.run();
}
}
}
Step by Step Solution
There are 3 Steps involved in it
1 Expert Approved Answer
Step: 1 Unlock
Question Has Been Solved by an Expert!
Get step-by-step solutions from verified subject matter experts
Step: 2 Unlock
Step: 3 Unlock
