表达式求值
Posted tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了表达式求值相关的知识,希望对你有一定的参考价值。
/** * 表达式求值 * * @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); } } } }
以上是关于表达式求值的主要内容,如果未能解决你的问题,请参考以下文章