资源描述:
《利用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;}privatevoidop
2、erate(Stringx){doublex1=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{re
3、sult="Thedivisorcan''tbezero!";}break;}}publicStringopAdd(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;re
4、turnresult;}publicStringopEquals(Stringx){operate(x);op=0;returnresult;}publicvoidopClean(){op=0;result="0";}}[Copytoclipboard]-------------------------------------------------------------------第二个CalculatorGUI.javaCODE:importjava.awt.*;importjava.awt.event.*;importjava.util.E
5、ventObject;publicclassCalculatorGUI{privateFramef;privatePanelp1,p2;privateButtonb0,b1,b2,b3,b4,b5,b6,b7,b8,b9;privateButtonbPoint,bAdd,bDec,bMul,bDiv,bCal;privateTextFieldtf;privateStrings,op;privateCalculatorcal=newCalculator();privatebooleanifOp;publicCalculatorGUI(){f=newF
6、rame("Calculator");p1=newPanel();p2=newPanel();b0=newButton("0");b1=newButton("1");b2=newButton("2");b3=newButton("3");b4=newButton("4");b5=newButton("5");b6=newButton("6");b7=newButton("7");b8=newButton("8");b9=newButton("9");bPoint=newButton(".");bAdd=newButton("+");bDec=new
7、Button("-");bMul=newButton("*");bDiv=newButton("/");bCal=newButton("=");tf=newTextField(25);tf.setEditable(false);}publicvoidlaunchFrame(){f.setSize(220,160);f.setResizable(false);f.addWindowListener(newmyWindowListener());p1.setLayout(newFlowLayout(FlowLayout.CENTER));p1.add(
8、tf);f.add(p1,BorderLayout.NORTH);p2.setLayout(newGridLayout(4