TDT4100/src/main/java/encapsulation/RPNCalc.java

58 lines
1.3 KiB
Java

package encapsulation;
import java.util.EmptyStackException;
import java.util.Stack;
public class RPNCalc {
// Using stack instead of Deque in order to get access to elementAt(i)
private Stack<Double> stack = new Stack<Double>();
public void push(double num) {
this.stack.push(num);
}
public double pop() {
Double result = this.stack.pop();
return result.isNaN() ? Double.NaN : result;
}
public double peek(int i) {
return this.getSize() >= (i + 1) && i >= 0
? this.stack.elementAt(this.getSize() - 1 - i)
: Double.NaN;
}
public int getSize() {
return this.stack.size();
}
public void performOperation(char op) throws IllegalArgumentException {
double a, b;
try {
a = this.stack.pop();
b = this.stack.pop();
} catch (EmptyStackException e) {
throw new IllegalArgumentException("Not enough numbers in the calculator");
}
switch (op) {
case '+':
this.stack.push(b + a);
break;
case '-':
this.stack.push(b - a);
break;
case '*':
this.stack.push(b * a);
break;
case '/':
this.stack.push(b / a);
break;
case '^':
this.stack.push(Math.pow(a, b));
break;
default:
throw new IllegalArgumentException("No such operator implemented: " + op);
}
}
}