/** * 编写一个计算器,能够四则混合运算。不支持负数和括号的算式。 * 用栈来实现此功能. * 例如:输入:1-0.5*5+1/2+3,输出:2.0 * */ import java.util.*; public class Calc{ private static Stack<Double> num=new Stack<Double>(); //存储操作数 private static Stack<Character> op=new Stack<Character>();//存储操作符 private static Map<Character,Integer> cmp=new HashMap<Character,Integer>(); //符号映射表 private static void setMap(){ cmp.put('+',1); //+代表运算优先级为1,数字越大,优先级越高 cmp.put('-',2); cmp.put('*',3); cmp.put('/',4); } public static void main(String[] args) { setMap(); Scanner sr=new Scanner(System.in); System.out.println("请输入表达式(例如:1-0.5*5+1/2+3):"); String exp=sr.next(); System.out.println(exp+"="+computer(exp)); } /* * 计算表达式 */ public static double computer(String exp){ char ch; char op_top; StringBuffer buf; for(int i=0;i<exp.length();){ ch=exp.charAt(i); buf=new StringBuffer(); if(Character.isDigit(ch)){ //判断当前字符是否数字,获取操作数。 buf.append(ch); i++; while(i<exp.length() && Character.isDigit(exp.charAt(i))){ buf.append(exp.charAt(i)); i++; } if(i<exp.length()&&(ch=exp.charAt(i))=='.') { buf.append(ch); i++; while(i<exp.length() && Character.isDigit(exp.charAt(i))){ buf.append(exp.charAt(i)); i++; } } num.push(Double.parseDouble(buf.toString())); } else{ while(!op.isEmpty()){ //当前操作符栈不为空 op_top=op.peek(); if(compareToOP(ch,op_top)>=1){ break; } else { op_top=op.pop(); switch(op_top){ case '+': num.push(num.pop()+num.pop());break; case '-': double a=num.pop();double b=num.pop();num.push(b-a);break; case '*':num.push(num.pop()*num.pop());break; case '/':double a1=num.pop();double b1=num.pop();num.push(b1/a1);break; default:System.out.println("出现未知符号!"); } } } if(ch!=')'){ op.push(ch); i++; } } } /* * 依次弹出剩余在栈操作符中的符号并进行运算 */ while(!op.isEmpty()){ op_top=op.pop(); switch(op_top){ case '+': num.push(num.pop()+num.pop());break; case '-': double a=num.pop();double b=num.pop();num.push(b-a);break; case '*':num.push(num.pop()*num.pop());break; case '/':double a1=num.pop();double b1=num.pop();num.push(b1/a1);break; default:System.out.println("出现未知符号!"); } } return num.pop(); } public static int compareToOP(char a,char b){ return cmp.get(a)-cmp.get(b); } }