目前我有一个程序可以将中缀表达式转换为后缀表达式。但是,我希望我的后缀输出如下所示:
中缀表达式:(11+11)*(11+11)
当前后缀表达式:11 11+ 11 11+*
所需的后缀表达式:11 11 + 11 11 + *
我不太清楚应该对代码进行哪些更改才能实现我想要的结果。
我的代码:
private int Prec(Character ch)
{
switch (ch)
{
case '+':
case '-':
return 1;
case '*':
case '/':
case '%':
return 2;
}
return 0;
}
@Override public T visitEval(ExpAnalyserParser.EvalContext ctx) {
String postfix = new String("");
Stack<Character> stack = new Stack<>();
for (int i = 0; i< ctx.getText().length(); i++) {
char c = ctx.getText().charAt(i);
if (Character.isDigit(c)) {
postfix += c;
}
else if (c == '(')
stack.push(c);
else if (c == ')') {
while (!stack.isEmpty() && stack.peek() != '(')
postfix += (stack.pop());
if (!stack.isEmpty() && stack.peek() != '(')
System.out.println("Invalid Expression");
else
stack.pop();
}
else {
postfix += " ";
while (!stack.isEmpty() && Prec(c) <= Prec(stack.peek()))
postfix += (stack.pop());
stack.push(c);
}
}
while (!stack.isEmpty()){
postfix += (stack.pop());
}
try(FileWriter out = new FileWriter("postfix.txt")){
out.write(postfix.toString());
out.close();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Infix Expression: " + ctx.getText());
return (T) postfix;
}
最佳答案
while (!stack.isEmpty() && Prec(c) <= Prec(stack.peek()))
postfix += " " + (stack.pop());
在添加操作符的任何地方添加操作符之前添加一个额外的空格
关于java - 从中缀表达式转换为后缀表达式后表达式之间的正确间距,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48844327/