Skip to content

fix: handle inputs like "2 +" in StackPostfixNotation #4262

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@ public static int postfixEvaluate(final String exp) {
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();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,4 +30,14 @@ public void testIfEvaluateThrowsExceptionForInproperInput() {
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 +"));
}
}