Question

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).

Était-ce utile?

La solution

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.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top