Reputation: 23
Good day! I am implementing an infix to postfix converter using stacks. It works when the user input an infix expression with no parenthesis; but when a parenthesis is present, the console says:
Exception in thread "main" StackEmptyException: Stack is empty.
at ArrayStack.top(ArrayStack.java:85)
at InfixToPostfix.convert(InfixToPostfix.java:54)
at InfixToPostfix.main(InfixToPostfix.java:85)
My problem is in implementing the rank (top of the stack).
Upvotes: 0
Views: 619
Reputation: 14164
Aha! You need "stack peek" when comparing rank of topmost.. because "top" must be popping the element off.
Try stack.peek() or equivalent. What actually class & library are you using, for the stack? s[top]
is not valid syntax.
Back at answer #1, I started to write a peekRank()
function for you, thinking there was an issue with checking when the stack was empty.. but stopped when I saw you had an empty-check.
It appears you weren't peek()ing the top correctly, though.
[Earlier #2 -- Not the issue]
Have you considered the ) handling? Your ( code appears to have a guard for stack-empty on it.
[Earlier # 1-- Not exactly the issue]
Put an 'ENTIRE EXPRESSION' pseudo-token on the stack for the entire duration of processing, so you have a non-empty stack, or answer a rank despite there being no surrounding expression/ enclosing token.
Upvotes: 0