所以我试图在Java中实现Shunting-yard算法,我做得很好,但我的问题是我希望由算法评估的文本字符串包含多于一位的数字。
我有这个问题的解决方案,但解决方案并不是那么“漂亮”。我能做的是,每当找到一个数字时(在主 for 循环中),我会将它连接到一个字符串并将一个布尔变量变为 true,以让程序知道我们在一个数字内。当 for 循环找到一个非数字字符时,布尔变量将变为 false,我们照常继续算法。
我觉得这个解决方案不是很好,因为每当我遇到困难时,将布尔变量 true/false 一直是我的解决方案。
请问有什么帮助吗?
while there are tokens to be read:
read a token.
**if the token is a number**, then push it to the output queue.
if the token is an operator, then:
while there is an operator at the top of the operator stack with
greater than or equal to precedence:
pop operators from the operator stack, onto the output queue;
push the read operator onto the operator stack.
if the token is a left bracket (i.e. "("), then:
push it onto the operator stack.
if the token is a right bracket (i.e. ")"), then:
while the operator at the top of the operator stack is not a left bracket:
pop operators from the operator stack onto the output queue.
pop the left bracket from the stack.
/* if the stack runs out without finding a left bracket, then there are
mismatched parentheses. */
if there are no more tokens to read:
while there are still operator tokens on the stack:
/* if the operator token on the top of the stack is a bracket, then
there are mismatched parentheses. */
pop the operator onto the output queue.
exit.
我已经突出显示了算法中出现问题的那一行(第 3 行)。它说数字,但我实现算法的方式只能捕获数字。
谢谢!