File tree Expand file tree Collapse file tree
main/java/com/thealgorithms/others
test/java/com/thealgorithms/others Expand file tree Collapse file tree Original file line number Diff line number Diff 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 ();
Original file line number Diff line number Diff 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}
You can’t perform that action at this time.
0 commit comments