我正在创建一个反向波兰语表示法计算器,该计算器将中缀表达式转换为后缀表达式。但是,我的运算符向后输出。例如,我输入的中缀为“ 1 + 5 *(3 * 2)”,当我运行程序时,当输出应为“ 1 5 3 2 +”时,输出为“ +1 + * * 3 2 5” * +”,我不知道为什么。
public class RPNcalc extends Stack
{
public static void main( String[] args)
{
String infix = "1+5*(3*2)";
RPNcalc test = new RPNcalc();
String output = test.ConvertToPostfix(infix);
System.out.println(output);
}
public static String ConvertToPostfix(String infix)
{
Stack stack1 = new Stack();
char ch;
String postfix = "";
for (int i = 0; i < infix.length(); i++)
{
ch = infix.charAt(i);
if (isOperator(ch))
{
postfix = postfix + ch + " ";
}
else if (ch == '(')
{
stack1.push(ch);
}
else if (ch == ')')
{
while (stack1.peek() != '(')
{
postfix = postfix + stack1.pop() + " ";
}
stack1.pop();
}
else
{
while (!stack1.isEmpty() && !(stack1.peek() == '(') && (precedence(ch) <= precedence(stack1.peek())))
{
postfix = postfix + stack1.pop() + " ";
}
stack1.push(ch);
}
}
while (!stack1.isEmpty())
{
postfix = postfix + stack1.pop();
}
return postfix;
}
答案 0 :(得分:1)
仅缺少一个“!”:
它必须显示为:
if( ! isOperator( ch ) ) {…}
,输出正确:
1 5 3 2 * * +
评估为31
*和+之间的间距出问题了
postfix + ' ' + stack1.pop()
吗?
在这里可以找到关于调车场算法的很好描述:
https://en.wikipedia.org/wiki/Shunting-yard_algorithm#Detailed_example
顺便说一句–在Java中,函数名称应以小写字母开头:
convertToPostfix( String infix )