1

逆ポーランド記法文字列を返すメソッドgetRPNString()があります。この文字列をスペースバーで分割して計算したいと思います。2 桁の数字では機能しないため、RNP 文字列にスペースバーを追加する方法がわかりません。

public class Calc1 {

public static void main(String[] args) {

    String in = "((5+3*(4+2)*12)+3)/(1+3)+5";
    String out = getRPNString(in);
    System.out.println(out);

}

private static String getRPNString(String in) {
    LinkedList<Character> oplist = new LinkedList<>();
    StringBuilder out = new StringBuilder();

    for (int i = 0; i < in.length(); i++) {
        char op = in.charAt(i);
        if (op == ')') {
            while (oplist.getLast() != '(') {
                out.append(oplist.removeLast());
            }
            oplist.removeLast();
        }

        if (Character.isDigit(op)) {

            out.append(op);

            /*int j = i + 1;
            for (; j < in.length(); j++) {
                if (!Character.isDigit(j)) {
                    break;
                }
                i++;
            }
            out.append(in.substring(i, j));*/

        }

        if (op == '(') {
            oplist.add(op);
        }

        if (isOperator(op)) {
            if (oplist.isEmpty()) {
                oplist.add(op);
            } else {
                int priority = getPriority(op);
                if (priority > getPriority(oplist.getLast())) {
                    oplist.add(op);
                } else {
                    while (!oplist.isEmpty()
                            && priority <= getPriority(oplist.getLast())) {
                        out.append(oplist.removeLast());
                    }
                    oplist.add(op);
                }
            }
        }

    }

    while (!oplist.isEmpty()) {
        out.append(oplist.removeLast());
    }

    return out.toString();
}

private static boolean isOperator(char c) {
    return c == '+' || c == '-' || c == '*' || c == '/' || c == '%';
}

private static int getPriority(char op) {
    switch (op) {

    case '*':
    case '/':
        return 3;

    case '+':
    case '-':
        return 2;

    case '(':
        return 1;

    default:
        return -1;
    }
}

}

StringBuilder 変数 out に append(' ') でスペースバーを追加しようとしました。でも二桁じゃダメ。作り方が全くわからないと思います。

たとえば、入力が文字列の場合 = "((5+3*(4+2)*12)+3)/(1+3)+5"; すべての呼び出しにスペースバーを追加すると、out は5342+ 12 +3+13+/5+になりますout.append(' ')**out は **5 3 4 2 + * 1 2 * + 3 + 1 3 + / 5 +なので、「12」のような数字は「1 2」になりました。手伝ってくれますか?

4

2 に答える 2