资源描述:
《利用java做一个简单的计算器》由会员上传分享,免费在线阅读,更多相关内容在学术论文-天天文库。
1、利用java做一个简单的计算器2007-4-27 网友评论7条 点击进入论坛两个类。还只是完成+、-、×、÷运算而已。GUI只是用了AWT,很简单,相信一看就能懂了。Calculator.javaCODE:publicclassCalculator{privateStringresult="0";privateintop=0,add=1,sub=2,mul=3,div=4;privatedoublestringToDouble(Stringx){doubley=Double.parseDouble(x);returny;}privatevoidoperate(Stringx){double
2、x1=stringToDouble(x);doubley=stringToDouble(result);switch(op){case0:result=x;break;case1:result=String.valueOf(y+x1);break;case2:result=String.valueOf(y-x1);break;case3:result=String.valueOf(y*x1);break;case4:if(x1!=0){result=String.valueOf(y/x1);}else{result="Thedivisorcan''tbezero!";}break;}}pu
3、blicStringopAdd(Stringx){operate(x);op=add;returnresult;}publicStringopSubtract(Stringx){operate(x);op=sub;returnresult;}publicStringopMultiply(Stringx){operate(x);op=mul;returnresult;}publicStringopDivide(Stringx){operate(x);op=div;returnresult;}publicStringopEquals(Stringx){operate(x);op=0;retur
4、nresult;}publicvoidopClean(){op=0;result="0";}}[Copytoclipboard]-------------------------------------------------------------------第二个CalculatorGUI.javaCODE:importjava.awt.*;importjava.awt.event.*;importjava.util.EventObject;publicclassCalculatorGUI{privateFramef;privatePanelp1,p2;privateButtonb0,
5、b1,b2,b3,b4,b5,b6,b7,b8,b9;privateButtonbPoint,bAdd,bDec,bMul,bDiv,bCal;privateTextFieldtf;privateStrings,op;privateCalculatorcal=newCalculator();privatebooleanifOp;publicCalculatorGUI(){f=newFrame("Calculator");p1=newPanel();p2=newPanel();b0=newButton("0");b1=newButton("1");b2=newButton("2");b3=n
6、ewButton("3");b4=newButton("4");b5=newButton("5");b6=newButton("6");b7=newButton("7");b8=newButton("8");b9=newButton("9");bPoint=newButton(".");bAdd=newButton("+");bDec=newButton("-");bMul=newButton("*");bDiv=newButton("/");bCal=newButton("=");tf=newTextField(25);tf.setEditable(false);}publicvoidl
7、aunchFrame(){f.setSize(220,160);f.setResizable(false);f.addWindowListener(newmyWindowListener());p1.setLayout(newFlowLayout(FlowLayout.CENTER));p1.add(tf);f.add(p1,BorderLayout.NORTH);p2.setLayout(newGridLayout(4