首页 > 代码库 > 表达式求值

表达式求值

/** * 表达式求值 *  * @author sun * */public class Expression {    public static void main(String[] args) {        // 定义优先级        Map<Character, Integer> map = new HashMap<Character, Integer>();        map.put(‘(‘, 0);        map.put(‘+‘, 1);        map.put(‘-‘, 1);        map.put(‘*‘, 2);        map.put(‘/‘, 2);        Stack<Integer> data = http://www.mamicode.com/new Stack<Integer>();// 数据栈        Stack<Character> op = new Stack<Character>();// 运算符栈        Scanner scanner = new Scanner(System.in);        String s = scanner.nextLine();        char[] charArray = s.toCharArray();        for (int i = 0; i < charArray.length; i++) {            if (charArray[i] >= ‘0‘ && charArray[i] <= ‘9‘) {                data.push((int) (charArray[i] - ‘0‘));            } else if (charArray[i] == ‘(‘) {                op.push((char) charArray[i]);            } else if (charArray[i] == ‘)‘) {                while (op.peek() != ‘(‘)                    calc(data, op);                op.pop();            } else {                while (!op.isEmpty() && map.get(charArray[i]) <= map.get(op.peek()))                    calc(data, op);                op.push(charArray[i]);            }        }        while (!op.isEmpty())            calc(data, op);        System.out.println(data.pop());    }    private static void calc(Stack<Integer> data, Stack<Character> op) {        int b = data.pop();        int a = data.pop();        char o = op.pop();        if (o == ‘-‘) {            data.push(a - b);        }        if (o == ‘+‘) {            data.push(a + b);        }        if (o == ‘*‘) {            data.push(a * b);        }        if (o == ‘/‘) {            if (b != 0)                data.push(a / b);            else {                data.push(0);            }        }    }}

 

表达式求值