今天扣丁学堂给介绍一下关于一款用Java语言写的简易计算器,希望对最近学习java的编程同学有所帮助,它可以实现基本的运算,测试目前无bug,下面我们一起来看下吧。
首先界面:
整个面板用了BorderLayout布局,分为北,左和中。中部采用网格布局。定义这个类位CalFrame.Java:
packagecom.example.java;
importjava.awt.BorderLayout;
importjava.awt.Color;
importjava.awt.Dimension;
importjava.awt.GridLayout;
importjava.awt.event.ActionEvent;
importjava.awt.event.ActionListener;
importjava.util.Arrays;
importjavax.swing.JButton;
importjavax.swing.JFrame;
importjavax.swing.JPanel;
importjavax.swing.JTextField;
publicclassCalFrameextendsJFrame{
/**
*计算器的外观设计
*/
privatestaticfinallongserialVersionUID=1L;
privatestaticfinalintPRE_WIDTH=500;
privatestaticfinalintPRE_HEIGHT=400;
privateJTextFieldtext=null;
privateJButtonbutton=null;//存储标记
privateString[]nOp={"7","8","9","/","sqrt","4","5","6","*","%","1","2","3","-","1/x","0","+/-",".","+","="};
privateString[]mOp={"MC","MR","MS","M+"};
privateString[]rOp={"Back","CE","C"};
privateCalServiceservice=newCalService();
publicCalFrame(){
this.setTitle("计算器");
this.setSize(PRE_WIDTH,PRE_HEIGHT);
this.setLocationRelativeTo(null);
this.setResizable(false);
//添加底层
JPanelpanel=newJPanel();
panel.setLayout(newBorderLayout(10,1));
panel.add(getTextField(),BorderLayout.NORTH);
panel.setPreferredSize(newDimension(PRE_WIDTH,PRE_HEIGHT));
//west
JButton[]mButton=getMButton();
JPanelpanel1=newJPanel();
panel1.setLayout(newGridLayout(5,1,0,5));
for(JButtonjButton:mButton){
panel1.add(jButton);
}
panel.add(panel1,BorderLayout.WEST);
JButton[]rButton=getRButton();
JPanelpanel2=newJPanel();
panel2.setLayout(newBorderLayout(1,5));
JPanelpanel21=newJPanel();
panel21.setLayout(newGridLayout(1,3,3,3));
for(JButtonjButton:rButton){
panel21.add(jButton);
}
panel2.add(panel21,BorderLayout.NORTH);
JButton[]nButton=getNButton();
JPanelpanel3=newJPanel();
panel3.setLayout(newGridLayout(4,5,3,5));
for(JButtonjButton:nButton){
panel3.add(jButton);
}
panel2.add(panel3,BorderLayout.CENTER);
panel.add(panel2,BorderLayout.CENTER);
this.add(panel);
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
this.setVisible(true);
}
//返回数字键
privateJButton[]getNButton(){
String[]redButton={"/","*","-","+","="};
JButton[]nbutton=newJButton[nOp.length];
for(inti=0;i<nOp.length;i++){
JButtonb=newJButton(this.nOp[i]);
b.addActionListener(getActionListener());
Arrays.sort(redButton);
if(Arrays.binarySearch(redButton,nOp[i])>=0){
b.setForeground(Color.red);
}else{
b.setForeground(Color.blue);
}
nbutton[i]=b;
}
returnnbutton;
}
privateJButton[]getRButton(){
JButton[]rButton=newJButton[rOp.length];
for(inti=0;i<rOp.length;i++){
JButtonb=newJButton(this.rOp[i]);
b.addActionListener(getActionListener());
b.setForeground(Color.red);
rButton[i]=b;
}
returnrButton;
}
//返回操作健
privateJButton[]getMButton(){
JButton[]mbutton=newJButton[mOp.length+1];
mbutton[0]=getButton();
for(inti=0;i<this.mOp.length;i++){
JButtonb=newJButton(this.mOp[i]);
b.addActionListener(getActionListener());
b.setForeground(Color.red);
mbutton[i+1]=b;
}
returnmbutton;
}
privateActionListenergetActionListener(){
ActionListeneractionListener=newActionListener(){
@Override
publicvoidactionPerformed(ActionEvente){
Stringcmd=e.getActionCommand();
Stringresult=null;
try{
result=service.callMethod(cmd,text.getText());
}catch(Exceptione2){
System.out.println(e2.getMessage());
}
if(cmd.indexOf("MC")==0){
button.setText("");
}elseif(cmd.indexOf("M")==0){
button.setText("M");
}
//显示计算结果
if(result!=null){
text.setText(result);
}
}
};
returnactionListener;
}
privateJButtongetButton(){
button=newJButton();
returnbutton;
}
//返回显示框
publicJTextFieldgetTextField(){
text=newJTextField("0",10);
returntext;
}
publicstaticvoidmain(String[]args){
newCalFrame();
}
}
接着实现几个基本的操作,加,减,乘,除。考虑到精度和范围的问题.我们定义了一个MyMath类,数据格式使用BigDecimal对象,进行计算。MyMath.java:
packagecom.example.java;
importjava.math.BigDecimal;
publicclassMyMath{
publicstaticdoubleadd(doublenum1,doublenum2){
BigDecimalfirst=getBigDecimal(num1);
BigDecimalsecond=getBigDecimal(num2);
returnfirst.add(second).doubleValue();
}
publicstaticdoubledivide(doublenum1,doublenum2){
BigDecimalfirst=getBigDecimal(num1);
BigDecimalsecond=getBigDecimal(num2);
returnfirst.divide(second,3,BigDecimal.ROUND_HALF_UP).doubleValue();
}
publicstaticdoublemultiply(doublenum1,doublenum2){
BigDecimalfirst=getBigDecimal(num1);
BigDecimalsecond=getBigDecimal(num2);
returnfirst.multiply(second).doubleValue();
}
publicstaticdoublesubtract(doublenum1,doublenum2){
BigDecimalfirst=getBigDecimal(num1);
BigDecimalsecond=getBigDecimal(num2);
returnfirst.subtract(second).doubleValue();
}
/**
*为一个double类型创建BigDecimal对象
*@paramnumber
*@return
*/
privatestaticBigDecimalgetBigDecimal(doublenumber){
returnnewBigDecimal(number);
}
123456789101112131415161718192021222324252627282930313233343536373839
}
最后处理按钮的事件,我们定义了一个CalService类处理业务逻辑:
packagecom.example.java;
/**
*处理业务逻辑
*@authorl
*
*/
publicclassCalService{
privatebooleanisSecondNum=false;
privateStringlastOp;
privateStringfirstNum="0";
privateStringsecondNum="null";
privatedoublestore;
privateStringnumString="0123456789.";
privateStringopString="+-*/";
publicStringcallMethod(Stringcmd,Stringtext){
if(cmd.equals("C")){
returncleanAll();
}elseif(cmd.equals("CE")){
returnclear(text);
}elseif(cmd.equals("Back")){
returnbackSpace(text);
}elseif(numString.indexOf(cmd)!=-1){
returncatNum(cmd,text);
}elseif(opString.indexOf(cmd)!=-1){
returnsetOp(cmd,text);
}elseif(cmd.equals("+/-")){
returnsetNegative(text);
}elseif(cmd.equals("1/x")){
returnsetReciprocal(text);
}elseif(cmd.equals("sqrt")){
returnsqrt(text);
}elseif(cmd.equals("%")){
returncal(text,true);
}elseif(cmd.equals("=")){
returncal(text,false);
}else{
returnmCmd(cmd,text);
}
}
privateStringcleanAll(){
this.firstNum="0";
this.secondNum=null;
returnthis.firstNum;
}
privateStringclear(Stringtext){
return"0";
}
privateStringbackSpace(Stringtext){
returntext.equals("0")||text.equals("")?"0":text.substring(0,text.length()-1);
}
privateStringcatNum(Stringcmd,Stringtext){
Stringresult=cmd;
//如果text不等于0
if(!"0".equals(text)){
if(isSecondNum){
isSecondNum=false;
}else{
result=text+cmd;
}
}
if(result.indexOf(".")==0){
result="0"+result;
}
returnresult;
}
privateStringsetOp(Stringcmd,Stringtext){
this.lastOp=cmd;
this.firstNum=text;
this.secondNum=null;
this.isSecondNum=true;
returnnull;
}
privateStringsetNegative(Stringtext){
if(text.indexOf("-")==0){
returntext.substring(1,text.length());
}else{
return"-"+text;
}
}
//求倒数
privateStringsetReciprocal(Stringtext){
if(text.equals("0")){
returntext;
}else{
this.isSecondNum=true;
returnString.valueOf(MyMath.divide(1,Double.valueOf(text)));
}
}
//求开方
privateStringsqrt(Stringtext){
this.isSecondNum=true;
returnString.valueOf(Math.sqrt(Double.valueOf(text)));
}
privateStringcal(Stringtext,booleanisPercent){
doublesecondResult=secondNum==null?Double.valueOf(text).doubleValue():Double.valueOf(secondNum).doubleValue();
//除数为0
if(secondResult==0&&this.lastOp.equals("/")){
return"0";
}
//有%
if(isPercent){
secondResult=MyMath.multiply(Double.valueOf(firstNum),MyMath.divide(secondResult,100));
}
if(this.lastOp.equals("+")){
firstNum=String.valueOf(MyMath.add(Double.valueOf(firstNum),secondResult));
}elseif(this.lastOp.equals("-")){
firstNum=String.valueOf(MyMath.subtract(Double.valueOf(firstNum),secondResult));
}elseif(this.lastOp.equals("*")){
firstNum=String.valueOf(MyMath.multiply(Double.valueOf(firstNum),secondResult));
}elseif(this.lastOp.equals("/")){
firstNum=String.valueOf(MyMath.divide(Double.valueOf(firstNum),secondResult));
}
secondNum=secondNum==null?text:secondNum;
this.isSecondNum=true;
returnfirstNum;
}
//存储
privateStringmCmd(Stringcmd,Stringtext){
if(cmd.equals("M+")){
store=MyMath.add(store,Double.valueOf(text));
}elseif(cmd.equals("MC")){
store=0;
}elseif(cmd.equals("MR")){
isSecondNum=true;
returnString.valueOf(store);
}elseif(cmd.equals("MS")){
store=Double.valueOf(text).doubleValue();
}
returnnull;
}
}
最后的calMethod方法大量使用ifelse判断不是好的实现方法,感兴趣的可以看看java的设计模式,消除这样的判断。最后想要了解更多关于Java发展前景趋势,请关注扣丁学堂Java培训官网、微信等平台,扣丁学堂IT职业在线学习教育平台为您提供权威的Java视频教程系统,通过千锋扣丁学堂金牌讲师在线录制的Java在线视频课程,让你快速掌握Java从入门到精通开发实战技能。扣丁学堂Java技术交流群:850353792。