資源描述:
《java編寫的計算器》由會員上傳分享,免費(fèi)在線閱讀,更多相關(guān)內(nèi)容在應(yīng)用文檔-天天文庫。
1、importjava.awt.*;importjava.awt.event.*;importjavax.swing.*;publicclassCalculatorextendsJFrameimplementsActionListener{privateJTextFieldtext;//顯示計算結(jié)果的文本行privatecharop;//當(dāng)前運(yùn)算符privatedoublevalue;//當(dāng)前計算結(jié)果值privatebooleanfirst;//表示是否為數(shù)值的第1個數(shù)字privatebooleancal;//是否為連續(xù)運(yùn)算booleanclickable;/
2、/控制運(yùn)算符是否可用booleanisTrue;//控制數(shù)字鍵是否可用intsign;//標(biāo)志是什么原因?qū)е庐惓ublicCalculator(){//TODOAuto-generatedconstructorstubsuper("計算器");this.setSize(280,210);this.setLocation(300,240);this.setDefaultCloseOperation(EXIT_ON_CLOSE);text=newJTextField("0.",30);text.setHorizontalAlignment(JTextField
3、.RIGHT);//設(shè)置對齊方式,右對齊text.setEditable(false);//只能顯示,不允許編輯this.getContentPane().add(text,"North");JPanelpanel=newJPanel(newGridLayout(5,4,5,5));//面板采用網(wǎng)格布局this.getContentPane().add(panel);Stringstr[]={"sqrt","+/-","Backspace","C","7","8","9","/","4","5","6","*","1","2","3","-","0","."
4、,"=","+"};JButtonbuttons[]=newJButton[str.length];for(inti=0;i5、display()//將多個按鈕中涉及到連續(xù)運(yùn)算的相同的代碼部分提出來單獨(dú)作為一個方法{switch(op)//當(dāng)按下第二個運(yùn)算符時,進(jìn)行前一個運(yùn)算符的運(yùn)算{case'+':value+=Double.parseDouble(text.getText());break;//轉(zhuǎn)換成浮點(diǎn)數(shù)后運(yùn)算case'-':value-=Double.parseDouble(text.getText());break;case'*':value*=Double.parseDouble(text.getText());break;case'/':if(Double.parseD
6、ouble(text.getText())==0){this.sign=1;clickable=false;isTrue=false;thrownewArithmeticException();}elsevalue/=Double.parseDouble(text.getText());break;}}publicvoidactionPerformed(ActionEvente)//按鈕單擊的事件處理方法{Stringcurrent=e.getActionCommand();//獲取按鈕標(biāo)簽try{if(current=="C")//清除{text.setT
7、ext("0.");//重新設(shè)置文本內(nèi)容value=0.0d;first=true;cal=false;//取消連續(xù)運(yùn)算標(biāo)記clickable=false;//設(shè)置運(yùn)算符此時不可用isTrue=true;return;}if(current=="Backspace"&&clickable==true)//退格{StringBufferstr1=newStringBuffer(text.getText());if(!text.getText().trim().equals("0.")){//如果文本框顯示的不是零if(str1.length()!=1){tex
8、t.setText(str1.delete(str1