Java 尝试将中缀转换为后缀将返回向后输出
我正在创建一个反向波兰符号计算器,它将中缀表达式转换为后缀表达式。但是,我的操作符正在向后输出。例如,我将中缀输入为“1+5*(3*2)”,当我运行程序时,我得到了输出“+1**3 2 5”,而它应该是“1 5 3 2++”,我不知道为什么Java 尝试将中缀转换为后缀将返回向后输出,java,postfix-notation,infix-notation,rpn,Java,Postfix Notation,Infix Notation,Rpn,我正在创建一个反向波兰符号计算器,它将中缀表达式转换为后缀表达式。但是,我的操作符正在向后输出。例如,我将中缀输入为“1+5*(3*2)”,当我运行程序时,我得到了输出“+1**3 2 5”,而它应该是“1 5 3 2++”,我不知道为什么 public class RPNcalc extends Stack { public static void main( String[] args) { String infix = "1+5*(3*2)"; RP
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;
}
公共类RPNcalc扩展堆栈
{
公共静态void main(字符串[]args)
{
字符串中缀=“1+5*(3*2)”;
RPNcalc测试=新的RPNcalc();
字符串输出=test.ConvertToPostfix(中缀);
系统输出打印项次(输出);
}
公共静态字符串ConvertToPostfix(字符串中缀)
{
Stack stack1=新堆栈();
char ch;
字符串后缀=”;
对于(int i=0;i 虽然(!stack1.isEmpty()&&!(stack1.peek()=='(')&&(优先级(ch)只缺少一个“!”:
它必须是:
if(!isOperator(ch)){…}
并且输出是正确的:
1 5 3 2**+
计算结果为31
*和+
之间的间距有问题
postfix+''+stack1.pop()
调车场算法的详细说明如下:
顺便说一下,在Java中,函数名应该以小写字母开头:
convertToPostfix(字符串中缀)