From a0d1e71ed56c75542545806be76127c48b1d9717 Mon Sep 17 00:00:00 2001 From: h7x4 Date: Sun, 5 Sep 2021 19:29:09 +0200 Subject: [PATCH] Implement calculator logic --- .../src/main/java/oysteikt/calc/Calc.java | 20 ++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/oysteikt-calc/src/main/java/oysteikt/calc/Calc.java b/oysteikt-calc/src/main/java/oysteikt/calc/Calc.java index cc90df3..6841127 100644 --- a/oysteikt-calc/src/main/java/oysteikt/calc/Calc.java +++ b/oysteikt-calc/src/main/java/oysteikt/calc/Calc.java @@ -74,8 +74,13 @@ public class Calc { * @throws IllegalStateException if the operand stack is empty */ public double performOperation(UnaryOperator op) throws IllegalStateException { - // TODO - return 0.0; + // if (this.getOperandCount() == 0) + if (this.operandStack.isEmpty()) + throw new IllegalStateException("Cannot perform operation " + op + " because of missing operands"); + + Double result = op.apply(this.popOperand()); + this.pushOperand(result); + return result; } /** @@ -103,7 +108,13 @@ public class Calc { * @throws IllegalStateException if the operand count is less than two */ public void swap() { + if (this.getOperandCount() < 2) + throw new IllegalStateException("Not enough operands to swap"); + Double x = this.popOperand(); + Double y = this.popOperand(); + this.pushOperand(x); + this.pushOperand(y); } /** @@ -112,6 +123,9 @@ public class Calc { * @throws IllegalStateException if the operand stack is empty */ public void dup() { - // TODO + if (this.operandStack.isEmpty()) + throw new IllegalStateException("Cannot duplicate top operand because there are no operands left"); + + this.pushOperand(this.peekOperand()); } } \ No newline at end of file