前几天去笔试了IDG,最后一题就是代码题表达式求值。
基本思路呢就是利用栈来进行运算,如果是数字就写入栈中,如果是运算符分两种情况
如果栈顶运算符的优先级比当前运算符优先级高,出栈并选择数据栈的2个元素进行计算并把计算结果写入数据栈中,新的运算符入栈.
代码如下
package com.pw.javase.study20140917; import java.util.Stack; /* * FileName:JavaSEPro * Description:表达式求值 * Created by:pengwei * date:2014/9/22 14:04 */ public class Calculate { //需要运算的表达式 private String expression; //需要运算的数字栈 private Stack digitalStack; //需要运算的数字栈 private Stack operatorStack; public Calculate(String expression) { this.expression = expression; digitalStack = new Stack(); operatorStack = new Stack(); System.out.println(expression + "\n运算结果:" + this.cal()); } private double cal() { String temp = ""; int count = expression.length(); for (int i = 0; i < count - 1; ++i) { Character c = expression.charAt(i); if (Character.isDigit(c) || c '.') { if (!temp.equals("")) { temp += c; } else { temp = c.toString(); } Character next = expression.charAt(i + 1); if (!Character.isDigit(next) && next != '.') { digitalStack.push(temp); temp = ""; } else if (i count - 2) { digitalStack.push(temp + next); } } else { if (operatorStack.size() 0) { operatorStack.push(c); } else { Character top = operatorStack.peek(); if (priority(top, c) 1) { operatorStack.push(c); } else { Character pop = operatorStack.pop(); operatorStack.push(c); double operate1 = Double.parseDouble(digitalStack.pop()); double operate2 = Double.parseDouble(digitalStack.pop()); double result = operate(operate2, operate1, pop); digitalStack.push(String.valueOf(result)); } } } } while (operatorStack.size() > 0) { Character pop = operatorStack.pop(); double operate1 = Double.parseDouble(digitalStack.pop()); double operate2 = Double.parseDouble(digitalStack.pop()); double result = operate(operate2, operate1, pop); digitalStack.push(String.valueOf(result)); } return Double.parseDouble(digitalStack.pop()); } /* * 比较运算符的优先级 * 0 相等 * 1 大于 * -1 小于 * * @param original * @param now * @return / private int priority(Character original, Character now) { int res = 0; if (original '' || original '/') { if (now '' || now '/') { res = 0; } else { res = -1; } } else if (original '+' || original '-') { if (now '' || now '/') { res = 1; } else { res = 0; } } return res; } /* * 根据运算符进行运算 * * @param a * @param b * @param o * @return */ private double operate(double a, double b, Character o) { double res = 0; switch (o) { case '': res = a * b; break; case '/': res = a / b; break; case '+': res = a + b; break; case '-': res = a - b; break; default: } return res; } public static void main(String[] args) { new Calculate("2+3*4/2+12.3"); } }