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

时间:2018-02-17 18:05:29

标签: java postfix-notation infix-notation

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

中缀表达:(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;
}

1 个答案:

答案 0 :(得分:1)

while (!stack.isEmpty() && Prec(c) <= Prec(stack.peek()))
                postfix += " " + (stack.pop());

在添加运算符的任何位置添加运算符之前添加额外空格