Skip to content

Commit e5c7a08

Browse files
authored
Handle inputs like "2 +" in StackPostfixNotation (#4262)
1 parent 44dcebb commit e5c7a08

File tree

2 files changed

+13
-0
lines changed

2 files changed

+13
-0
lines changed

src/main/java/com/thealgorithms/others/StackPostfixNotation.java

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,9 @@ public static int postfixEvaluate(final String exp) {
1616
if (tokens.hasNextInt()) {
1717
s.push(tokens.nextInt()); // If int then push to stack
1818
} else { // else pop top two values and perform the operation
19+
if (s.size() < 2) {
20+
throw new IllegalArgumentException("exp is not a proper postfix expression (too few arguments).");
21+
}
1922
int num2 = s.pop();
2023
int num1 = s.pop();
2124
String op = tokens.next();

src/test/java/com/thealgorithms/others/StackPostfixNotationTest.java

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,4 +30,14 @@ public void testIfEvaluateThrowsExceptionForInproperInput() {
3030
public void testIfEvaluateThrowsExceptionForInputWithUnknownOperation() {
3131
assertThrows(IllegalArgumentException.class, () -> StackPostfixNotation.postfixEvaluate("3 3 !"));
3232
}
33+
34+
@Test
35+
public void testIfEvaluateThrowsExceptionForInputWithTooFewArgsA() {
36+
assertThrows(IllegalArgumentException.class, () -> StackPostfixNotation.postfixEvaluate("+"));
37+
}
38+
39+
@Test
40+
public void testIfEvaluateThrowsExceptionForInputWithTooFewArgsB() {
41+
assertThrows(IllegalArgumentException.class, () -> StackPostfixNotation.postfixEvaluate("2 +"));
42+
}
3343
}

0 commit comments

Comments
 (0)