diff --git a/src/Computer.java b/src/Computer.java new file mode 100644 index 0000000..1e92811 --- /dev/null +++ b/src/Computer.java @@ -0,0 +1,129 @@ +import java.util.Stack; + +public class Computer { + public double result;//结果 + public Stack dataItem;//参与运算数据项 + public Stack tempResult;//中间结果 + public Stack operator;//运算符号 + + public Computer(){ + init(); + } + + public void init(){//初始化 + dataItem=new Stack(); + tempResult=new Stack(); + dataItem.push('0'); + operator=new Stack(); + } + + public double getResult() { + double endItem=0; + if(dataItem.empty()){ + endItem=tempResult.peek(); + }else{ + endItem=computerDataItem(); + } + if(operator.empty()){ + result=endItem; + return result; + } + char c=operator.peek(); + if (c == '+') { + result=tempResult.peek()+endItem; + }else if (c == '-') { + result=tempResult.peek()-endItem; + }else if (c == '*') { + result=tempResult.peek()*endItem; + }else if (c == '/') { + result=tempResult.peek()/endItem; + } + return result; + } + + + public void setDataItem(char c) { + //数据项中不包含小数点时才可以添加小数点 + if(c!='.') + dataItem.push(c); + else { + if(!dataItem.contains('.')) + dataItem.push(c); + } + } + + public double getTempResult() { + double t=0; + if(tempResult.empty()){ + t=computerDataItem(); + }else{ + t=tempResult.peek(); + } + return t; + } + + + public char getOperator() { + if(operator.empty()){ + return '\0'; + } + return operator.peek(); + } + + public void setOperator(char p) { + if(dataItem.empty()){ + operator.clear();//防止重复输入运算符 + operator.push(p);//保留用户最后确定的运算符 + return; + } + if(operator.empty()){ + operator.push(p); + double m=computerDataItem();//计算数据项 + dataItem.removeAllElements();//清空数据项中的数字 + tempResult.push(m);//临时结果压入tempResult + }else{ + double m1=computerDataItem(); + dataItem.removeAllElements(); + char c= operator.pop();//弹出已有的运算符 + double t=tempResult.pop();//弹出临时结果 + if (c == '+') { + t=t+m1; + }else if (c == '-') { + t=t-m1; + }else if (c == '*') { + t=t*m1; + }else if (c == '/') { + t=t/m1; + } + tempResult.push(t);//把新的结果压入tempResult + operator.push(p);//把新的运算符压入operator + } + } + + public double computerDataItem(){//计算出数据项的double型结果 + if(dataItem.empty()){ + return tempResult.peek(); + } + StringBuffer sb=new StringBuffer(); + double doubleData=0; + for (int i = 0; i < dataItem.size(); i++) { + sb.append(dataItem.get(i));//获取堆栈中的数字但不弹栈 + } + try { + doubleData=Double.parseDouble(sb.toString()); + }catch (NumberFormatException e){ + doubleData=0; + } + return doubleData; + } + public void backspace(){ + if(dataItem.size()>=1){ + dataItem.pop(); + } + } + + public void initMath(MathComputer mc){ + mc.handle(this); + } + +}