Java表达式求值

来源:互联网 发布:建筑工程绘图软件 编辑:程序博客网 时间:2024/05/20 23:03

Java表达式求解实现,用到栈先进后出的特点,详见代码

public float evaluation(String textField) {StringBuilder str = new StringBuilder();Stack<Float> stk = new Stack<Float>(); // 用于寄存操作数或结果Stack<Character> stk2 = new Stack<Character>(); // 用于寄存运算符stk2.push('#'); // 在运算符栈初始一个'#',用于第一个运算符比较优先级char c;// 依次读入字符for (int i = 0; i < textField.length(); i++) {boolean isbeg = false;// 是否为负数或正数操作符c = textField.charAt(i);if ((c >= '0' && c <= '9') || c == '.') { // 数字或小数点直接组合str.append(c);} else if (c == '+' || c == '-' || c == '*' || c == '/' || c == '('|| c == ')') {if ((c == '+' || c == '-') && stk.empty() && str.length() == 0) {str.append(c);isbeg = true;} else if (str.length() != 0) {try {float f = Float.parseFloat(str.toString());stk.push(f);} catch (Exception e) {flag = false;return -1;}str.delete(0, str.length());}// 如果读入操作符优先级小于操作符栈顶元素优先级,进行计算,并将结果保存如操作数栈if (judge(stk2.peek()) >= judge(c) && !isbeg) {try {float b = Float.parseFloat(stk.pop().toString());float a = Float.parseFloat(stk.pop().toString());// 取出操作数栈两数char c1 = stk2.pop();// 取出操作符if (c != ')') {stk2.push(c); // 低优先级操作符入栈}switch (c1) {case '+':stk.push(a + b);break;case '-':stk.push(a - b);break;case '*':stk.push(a * b);break;case '/':stk.push(a / b);break;default:break;}} catch (Exception e) {flag = false;return -1;}if (c == ')') {while (stk2.peek() != '#') {float b = Float.parseFloat(stk.pop().toString());try {float a = Float.parseFloat(stk.pop().toString());// 取出操作数栈两数char c1 = stk2.pop();// 取出操作符switch (c1) {case '+':stk.push(a + b);break;case '-':stk.push(a - b);break;case '*':stk.push(a * b);break;case '/':// if (b == 0) {// 除数为零// } else {stk.push(a / b);// }break;default:break;}} catch (Exception e) {flag = false;return -1;}}// stk2.pop();// 弹出')'stk2.pop();// 弹出'#'stk2.pop();// 弹出'('}} else if (!isbeg) {stk2.push(c);if (c == '(') {stk2.push('#');}}} else {flag = false;return -1;}}// 如果 以操作数结尾,将最后一操作数入栈if (str.length() > 0) {try {float f = Float.parseFloat(str.toString());stk.push(f);} catch (Exception e) {flag = false;return -1;}str.delete(0, str.length());}//最后个字符为"("if(stk2.peek()=='#'){flag=false;return -1;}while (stk2.peek() != '#') {try {float b = Float.parseFloat(stk.pop().toString());float a = Float.parseFloat(stk.pop().toString());// 取出操作数栈两数char c1 = stk2.pop();// 取出操作符switch (c1) {case '+':stk.push(a + b);break;case '-':stk.push(a - b);break;case '*':stk.push(a * b);break;case '/':// if (b == 0) {// 除数为零// } else {stk.push(a / b);// }break;default:break;}} catch (Exception e) {flag = false;return -1;}}try {return Float.parseFloat(stk.pop().toString());} catch (Exception e) {flag = false;return -1;}}

判断运算符优先级

// 判断优先级public static int judge(char c) {int n = 0;switch (c) {case '(':n = 3;break;case '+':case '-':n = 1;break;case '*':case '/':n = 2;break;case ')':n = 0;break;default:}return n;}