码迷,mamicode.com
首页 > 其他好文 > 详细

表达式求值

时间:2017-04-16 20:39:33      阅读:214      评论:0      收藏:0      [点我收藏+]

标签:scanner   []   log   public   表达式   ssi   next   empty   else   

/**
 * 表达式求值
 * 
 * @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 = 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);
            }
        }
    }
}

 

表达式求值

标签:scanner   []   log   public   表达式   ssi   next   empty   else   

原文地址:http://www.cnblogs.com/sunTin/p/6719549.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!