Handle inputs like "2 +" in StackPostfixNotation (#4262)

This commit is contained in:
Piotr Idzik
2023-07-26 13:11:28 +02:00
committed by GitHub
parent 44dcebb699
commit e5c7a08874
2 changed files with 13 additions and 0 deletions

View File

@ -16,6 +16,9 @@ public final class StackPostfixNotation {
if (tokens.hasNextInt()) { if (tokens.hasNextInt()) {
s.push(tokens.nextInt()); // If int then push to stack s.push(tokens.nextInt()); // If int then push to stack
} else { // else pop top two values and perform the operation } 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 num2 = s.pop();
int num1 = s.pop(); int num1 = s.pop();
String op = tokens.next(); String op = tokens.next();

View File

@ -30,4 +30,14 @@ public class StackPostfixNotationTest {
public void testIfEvaluateThrowsExceptionForInputWithUnknownOperation() { public void testIfEvaluateThrowsExceptionForInputWithUnknownOperation() {
assertThrows(IllegalArgumentException.class, () -> StackPostfixNotation.postfixEvaluate("3 3 !")); 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 +"));
}
} }