从中缀表达式转换为后缀表达式后更正表达式之间的间距
Correct spacing between expressions after converting from infix to postfix expression
目前我有一个将中缀表达式转换为后缀的程序。但是,我希望我的后缀输出是这样的:
中缀表达式:(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());
在添加运算符之前添加一个额外的 space
目前我有一个将中缀表达式转换为后缀的程序。但是,我希望我的后缀输出是这样的:
中缀表达式:(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());
在添加运算符之前添加一个额外的 space