문제

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

도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top