Java使用逆波兰表达式算法制作的表达式计算器
package com.infogrid.g2b;
import java.util.HashMap;
import java.util.Map;
public class Op {
private static final Map<String,Integer> ops = new HashMap<String, Integer>();
static{
ops.put("+",10);
ops.put("-",10);
ops.put("*",20);
ops.put("/",20);
ops.put("%",20);
ops.put("(",100);
ops.put(")",100);
}
public static boolean isSign(String sign1){
Integer s = ops.get(sign1);
if(s==null)
return false;
else
return true;
}
public static int compare(String sign1,String sign2){
Integer p1 = ops.get(sign1);
Integer p2 = ops.get(sign2);
if(p1==null)
throw new IllegalArgumentException("符号:"+sign1+"不存在!");
if(p2==null)
throw new IllegalArgumentException("符号:"+sign2+"不存在!");
return p1-p2;
}
public static Object cal(Object x,Object y,String sign){
Double a=0.0,b=0.0;
a = Double.valueOf(x+"");
b = Double.valueOf(y+"");
if(sign.equals("+"))
return a+b;
if(sign.equals("-"))
return a-b;
if(sign.equals("*"))
return a*b;
if(sign.equals("/"))
return a/b;
if(sign.equals("%"))
return a%b;
throw new IllegalArgumentException("操作符不合法!");
}
}
package com.infogrid.g2b;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public class Calculator {
private List list = new ArrayList();
private Stack stack = new Stack();
private List resolveExpr(String exp){
String opert=exp.replaceAll("\\d*\\.\\d+?", "");
List list=new ArrayList();
int pidx=-1;
for(int i=0;i<opert.length();i++){ String p=opert.substring(i, i+1); pidx=exp.indexOf(p); if(exp.substring(0,pidx).trim().length()!=0){ list.add(exp.substring(0, pidx)); } list.add(exp.substring(pidx, pidx+1)); exp=exp.substring(pidx+1); } if(exp.length()>0){
list.add(exp);
}
return list;
}
private void dealSign(String s){
if(stack.size()==0){
stack.push(s);
return;
}
String ps = stack.pop();
if(Op.compare(s, ps)>0||ps.equals("(")){
if(s.equals(")")){
list.add(ps);
while(stack.size()>0){
ps = stack.pop();
if(ps.equals("("))
break;
list.add(ps);
}
}else{
stack.push(ps);
stack.push(s);
}
}else{
list.add(ps);
dealSign(s);
}
}
private void dealVar(String s){
list.add(s);
}
private Double getResult(){
for(String s:list){
if(!Op.isSign(s)){
stack.push(s);
continue;
}
Object a = 0,b = 0;
if(stack.size()>0)
b = stack.pop();
if(stack.size()>0)
a = stack.pop();
stack.push(Op.cal(a, b, s)+"");
}
return Double.valueOf(stack.pop());
}
public Double calculate(String expression){
List ss = resolveExpr(expression);
for(String s:ss){
if(Op.isSign(s)){
dealSign(s);
}else{
dealVar(s);
}
}
while(stack.size()>0){
list.add(stack.pop());
}
System.out.println(list);
return getResult();
}
public static void main(String[] args) {
System.out.println(new Calculator().calculate("1.5+2.1+((4/2)-6/((2+1)*2))+6%4"));
}
}