Пробелы между элементами в выражении RPN java

У меня есть метод getRPNString(), который возвращает строку обратной польской нотации. Я хочу разделить эту строку пробелами, чтобы вычислить ее. Теперь я не могу понять, как правильно добавить пробелы в мою строку 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;
    }
}

}

Я попытался добавить пробелы с помощью append(' ') в моей переменной StringBuilder. Но это неправильно с двумя цифрами. Я думаю, что я совершенно не понимаю, как это сделать.

Например, если ввод String in = "((5+3*(4+2)*12)+3)/(1+3)+5"; выход будет 5342+12+3+13+/5+, когда я добавлю пробел ко всем вызовам out.append(' ')**out равно **5 3 4 2 + * 1 2 * + 3 + 1 3 + / 5 +, поэтому такие числа, как «12», стали «1 2». Вы можете помочь?


person dimads    schedule 24.02.2015    source источник


Ответы (2)


Просто измените код, который вы закомментировали, сразу после Character.isDigit(op) на:

int j = i + 1;
int oldI = i;//this is so you save the old value
for (; j < in.length(); j++) {
    if (!Character.isDigit(in.charAt(j))) {
        break;
    }
    i++;
}
out.append(in.substring(oldI, j));
out.append(' ');
person Deni Spasovski    schedule 24.02.2015

Я изменил свой метод, теперь он работает нормально. Я понял свою ошибку, когда написал !Character.isDigit(j), но мне нужен !Character.isDigit(in.charAt(j)).

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()).append(' ');
            }
            oplist.removeLast();
        }

        if (Character.isDigit(op)) {

            int j = i + 1;
            int oldI = i;//this is so you save the old value
            for (; j < in.length(); j++) {
                if (!Character.isDigit(in.charAt(j))) {
                    break;
                }

                i++;
            }

            out.append(in.substring(oldI, j));
            out.append(' ');

        }

        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()).append(' ');
                    }
                    oplist.add(op);
                }
            }
        }

    }

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

    return out.toString();
}

Теперь это производит правильное выражение. Тест: ввод: ((5+3*(4+2)*12)+3)/(1+3)+5 вывод: 5 3 4 2 + * 12 * + 3 + 1 3 + / 5 +

person dimads    schedule 25.02.2015