思路:
1 将表达式转换成后缀表达式
2 利用栈计算后缀表达式
/** * 计算数值 * @param text * @return */ public static int count(String text) { Queuequeue=changeToPostOrder(text); Stack stack=new Stack<>(); int result=0; while(!queue.isEmpty()) { String t=queue.poll(); if(t.length()>1)//数字 { stack.push(Integer.parseInt(t)); } else if(t.length()==1) { if(isYunsuanfu(t)) { char c=t.charAt(0); int ri=stack.pop(); int li=stack.pop(); switch (c) { case '+': result=li+ri; stack.push(result); break; case '-': result=li-ri; stack.push(result); break; case '*': result=li*ri; stack.push(result); break; case '/': result=li/ri; stack.push(result); break; default: break; } } else { stack.push(Integer.parseInt(t)); } } } return stack.empty()?0:stack.pop(); } //change to post order /** * 遇到数字直接输出,遇到符号,假如是高于栈顶优先级如乘除就直接压栈, * 假如是低于或等于栈顶优先级或者是右括号直接输出栈顶直到左括号,再压栈 * @param text * @return */ public static Queue changeToPostOrder(String text) { Queue queue=new LinkedList<>(); Stack stack=new Stack<>(); StringBuilder temp=new StringBuilder(); int len=text.length(); for(int i=0;i ='0' && c<='9'; } public static boolean isYunsuanfu(String s) { return s.equals("*") || s.equals("/") || s.equals("+") || s.equals("-"); } public static boolean isHigher(char c,char cmp) { return priority(c)>priority(cmp); } public static int priority(char c) { int p=0; switch (c) { case '*': p=2; break; case '/': p=2; break; case '+': p=1; break; case '-': p=1; break; default: break; } return p; }
程序很罗嗦,有空再写一遍!