java - 从中缀表达式转换为后缀表达式后表达式之间的正确间距

标签 java postfix-notation infix-notation

目前我有一个程序可以将中缀表达式转换为后缀表达式。但是,我希望我的后缀输出如下所示:

中缀表达式:(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/

相关文章:

java - 假设我有一个好的 key ,当不适合在java中使用 map 时

使用 strictfp 修饰符声明的 Java 类无法通过 Modifier.isStrict(int) 进行测试

stack - 堆栈的写时复制

评估前缀表达式的算法?

c - 无法找出我的代码中的逻辑错误

java - 声明接口(interface)方法仅允许实现的类

java - Wildfly 10.1.0 中的 session 问题

python - 程序不接受参数 Python

c - 从 C 中的前缀表达式构建解析树

c++ - 测试 C++ 后缀到中缀堆栈上操作数过多