为了账号安全,请及时绑定邮箱和手机立即绑定

使用java中的堆栈在中缀表达式中创建括号

使用java中的堆栈在中缀表达式中创建括号

万千封印 2022-06-04 16:55:56
我需要编写一个 Java 程序,从标准输入中获取有效的右括号中缀表达式 (RPIE) 并输出等效的全括号中缀表达式 (FPIE)。例如,如果输入是:a+20)/bc) 53.4-d))),则输出应该是 ((a+20)/((bc) (53.4-d)))。我尝试如下实施,但没有达到解决方案。有人可以帮我吗?import java.util.Scanner;import java.util.Stack;public class ParenthesisCreator {    static private String expression;    private Stack<Character> stack = new Stack<Character>();    public ParenthesisCreator(String input) {        expression = input;    }    public String rtParenthesisInfixToFullParenthesis() {        String postfixString = "";        for (int index = 0; index < expression.length(); ++index) {            char value = expression.charAt(index);            if (value == ')') {                stack.push(')');                 stack.push('(');                Character oper = stack.peek();                while (!stack.isEmpty()) {                    stack.pop();                    postfixString += oper.charValue();                    if (!stack.isEmpty())                                         oper = stack.peek();                 }            } else {                postfixString += value;            }        }        return postfixString;    }    public static void main(String[] args) {        System.out.println("Type an expression written in right parenthesized infix: ");        Scanner input = new Scanner(System.in);        String expression = input.next();        // Input: a+20)/b-c)*53.4-d)))        // Desired output is: ((a+20)/((b-c)*(53.4-d)))        ParenthesisCreator convert = new ParenthesisCreator(expression);        System.out.println("This expression writtien in full parenthesized is: \n" + convert.rtParenthesisInfixToFullParenthesis());    }}
查看完整描述

2 回答

?
慕桂英546537

TA贡献1848条经验 获得超10个赞

public final class ParenthesisCreator implements Function<String, String> {

    private final IntPredicate isOperator;


    public ParenthesisCreator() {

        this(ch -> ch == '/' || ch == '*' || ch == '+' || ch == '-');

    }


    public ParenthesisCreator(IntPredicate isOperator) {

        this.isOperator = isOperator;

    }


    @Override

    public String apply(String expr) {

        Deque<String> stack = new LinkedList<>();

        StringBuilder buf = null;


        for (int i = 0; i < expr.length(); i++) {

            char ch = expr.charAt(i);


            if (ch == ')') {

                if (buf != null) {

                    stack.push(buf.insert(0, '(').append(')').toString());

                    buf = null;

                } else if (stack.size() >= 2) {

                    String two = stack.pop();

                    String one = stack.pop();

                    stack.push('(' + one + two + ')');

                } else

                    throw new IllegalArgumentException();

            } else if (isOperator.test(ch) && buf == null && !stack.isEmpty())

                stack.push(stack.pop() + ch);

            else

                (buf = buf == null ? new StringBuilder() : buf).append(ch);

        }


        return String.join("", stack);

    }

}



System.out.println(new ParenthesisCreator().apply("a+20)/b-c)53.4-d)))"));    // ((a+20)/((b-c)(53.4-d)))



查看完整回答
反对 回复 2022-06-04
?
撒科打诨

TA贡献1934条经验 获得超2个赞

public class FixExpressionParentheses {


    public String fixExpression(String expression) {

        String[] tokenArray = expression.split(" ");


        Stack<String> operators = new Stack<>();

        Stack<String> operands = new Stack<>();


        for (String token: tokenArray) {

            switch (token) {

                case "+", "-", "*", "/", "sqrt" -> operators.push(token);

                case ")" -> {

                    String operator = operators.pop();

                    String operandTwo = operands.pop();

                    String operandOne = operands.pop();

                    String newToken = "( " + operandOne + " " + operator + " "

                                           + operandTwo + " )";

                    operands.push(newToken);

                }

                default -> operands.push(token);

            }

        }


        return operands.pop();

    }

}


查看完整回答
反对 回复 2022-06-04
  • 2 回答
  • 0 关注
  • 179 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号