JAVA 字符串的加减乘除 不包含括号

package com.lyjplus.app.modular.ceshi;

/**
 * @description:
 * @author: longyj
 * @create: 2020-04-21 21:14
 **/
public class Test {

    public static void main(String[] args) {
        /**
         * todo 此字符串为一个 四则运算表达是 不包含括号
         * todo 测试字符串 12+31 56*23 45+58-89 45+87-2*26 12+5*6/5-12
         */
        String str = "45+87-2*26/4";
        System.out.println(str + "=" + cal(str));
    }

    public static int cal(String str) {
        char[] temp   = str.toCharArray();
        int    len    = temp.length;
        char[] symbol = new char[len];
        int[]  value  = new int[len];
        int i = 0,j = 0;

        for (int k = 0; k < temp.length; k++) {
            if (isSymbol(temp[k])) {//是符号
                symbol[i++] = temp[k];
            } else {//不是符号
                StringBuffer buffer = new StringBuffer();
                while (k < temp.length && !isSymbol(temp[k])) {
                    buffer.append(temp[k]);
                    k++;
                }
                value[j++] = Integer.parseInt(new String(buffer));
                k--;
            }
        }
        i--;
        j--;
        for (int f_i = 0; f_i <= i; f_i++) {//遍历符号,先进行*和/的运算
            if (symbol[f_i] == '*') {
                value[f_i + 1] = value[f_i] * value[f_i + 1];
                value[f_i] = Integer.MAX_VALUE;
            } else if (symbol[f_i] == '/') {
                value[f_i + 1] = value[f_i] / value[f_i + 1];
                value[f_i] = Integer.MAX_VALUE;
            }
        }

        int up_i = 0, up_j = 0;
        char[] up_symbol = new char[i + 1];
        int[] up_value = new int[j + 1];
        for (int p = 0; p <= i; p++) {
            if (symbol[p] != '#')
                up_symbol[up_i++] = symbol[p];
        }
        for (int p = 0; p <= j; p++) {
            if (value[p] != Integer.MAX_VALUE)
                up_value[up_j++] = value[p];
        }
        //索引边界
        up_i--;up_j--;

        //后进行+和-的运算
        for (int y_i = 0; y_i <= up_i; y_i++)//遍历符号表
        {
            if (up_symbol[y_i] == '+') {
                up_value[y_i + 1] = up_value[y_i] + up_value[y_i + 1];
            } else if (up_symbol[y_i] == '-') {
                up_value[y_i + 1] = up_value[y_i] - up_value[y_i + 1];
            }
        }
        return up_value[up_j];
    }

    public static boolean isSymbol(char s) {
        if (s == '+' || s == '-' || s == '*' || s == '/')
            return true;
        else
            return false;
    }
}

你可能感兴趣的:(JAVA)