diff --git a/src/main/java/com/thealgorithms/others/StackPostfixNotation.java b/src/main/java/com/thealgorithms/others/StackPostfixNotation.java index c6d395cb0..f8591510e 100644 --- a/src/main/java/com/thealgorithms/others/StackPostfixNotation.java +++ b/src/main/java/com/thealgorithms/others/StackPostfixNotation.java @@ -16,6 +16,9 @@ public final class StackPostfixNotation { if (tokens.hasNextInt()) { s.push(tokens.nextInt()); // If int then push to stack } else { // else pop top two values and perform the operation + if (s.size() < 2) { + throw new IllegalArgumentException("exp is not a proper postfix expression (too few arguments)."); + } int num2 = s.pop(); int num1 = s.pop(); String op = tokens.next(); diff --git a/src/test/java/com/thealgorithms/others/StackPostfixNotationTest.java b/src/test/java/com/thealgorithms/others/StackPostfixNotationTest.java index 4894b403e..9256e2bc4 100644 --- a/src/test/java/com/thealgorithms/others/StackPostfixNotationTest.java +++ b/src/test/java/com/thealgorithms/others/StackPostfixNotationTest.java @@ -30,4 +30,14 @@ public class StackPostfixNotationTest { public void testIfEvaluateThrowsExceptionForInputWithUnknownOperation() { assertThrows(IllegalArgumentException.class, () -> StackPostfixNotation.postfixEvaluate("3 3 !")); } + + @Test + public void testIfEvaluateThrowsExceptionForInputWithTooFewArgsA() { + assertThrows(IllegalArgumentException.class, () -> StackPostfixNotation.postfixEvaluate("+")); + } + + @Test + public void testIfEvaluateThrowsExceptionForInputWithTooFewArgsB() { + assertThrows(IllegalArgumentException.class, () -> StackPostfixNotation.postfixEvaluate("2 +")); + } }