Java编写计算器的常见方法实例总结
本文实例总结了Java编写计算器的常见方法。分享给大家供大家参考,具体如下:
方法一:
packagewanwa; importjava.awt.*; importjava.awt.event.*; importjavax.swing.*; publicclassCalculatorextendsJFrame{ privateContainercontainer; privateGridBagLayoutlayout; privateGridBagConstraintsconstraints; privateJTextFielddisplayField;//计算结果显示区 privateStringlastCommand;//保存+,-,*,/,=命令 privatedoubleresult;//保存计算结果 privatebooleanstart;//判断是否为数字的开始 publicCalculator(){ super("Calculator"); container=getContentPane(); layout=newGridBagLayout(); container.setLayout(layout); constraints=newGridBagConstraints(); start=true; result=0; lastCommand="="; displayField=newJTextField(20); displayField.setHorizontalAlignment(JTextField.RIGHT); constraints.gridx=0; constraints.gridy=0; constraints.gridwidth=4; constraints.gridheight=1; constraints.fill=GridBagConstraints.BOTH; constraints.weightx=100; constraints.weighty=100; layout.setConstraints(displayField,constraints); container.add(displayField); ActionListenerinsert=newInsertAction(); ActionListenercommand=newCommandAction(); //addButton("Backspace",0,1,2,1,insert); //addButton("CE",2,1,1,1,insert); //addButton("C",3,1,1,1,insert); addButton("7",0,2,1,1,insert); addButton("8",1,2,1,1,insert); addButton("9",2,2,1,1,insert); addButton("/",3,2,1,1,command); addButton("4",0,3,1,1,insert); addButton("5",1,3,1,1,insert); addButton("6",2,3,1,1,insert); addButton("*",3,3,1,1,command); addButton("1",0,4,1,1,insert); addButton("2",1,4,1,1,insert); addButton("3",2,4,1,1,insert); addButton("-",3,4,1,1,command); addButton("0",0,5,1,1,insert); //addButton("+/-",1,5,1,1,insert);//只显示"-"号,"+"没有实用价值 addButton(".",2,5,1,1,insert); addButton("+",3,5,1,1,command); addButton("=",0,6,4,1,command); this.setResizable(false); setSize(180,200); setVisible(true); } privatevoidaddButton(Stringlabel,introw,intcolumn,intwith, intheight,ActionListenerlistener){ JButtonbutton=newJButton(label); constraints.gridx=row; constraints.gridy=column; constraints.gridwidth=with; constraints.gridheight=height; constraints.fill=GridBagConstraints.BOTH; button.addActionListener(listener); layout.setConstraints(button,constraints); container.add(button); } privateclassInsertActionimplementsActionListener{ publicvoidactionPerformed(ActionEventevent){ Stringinput=event.getActionCommand(); if(start){ displayField.setText(""); start=false; if(input.equals("+/-")) displayField.setText(displayField.getText()+"-"); } if(!input.equals("+/-")){ if(input.equals("Backspace")){ Stringstr=displayField.getText(); if(str.length()>0) displayField.setText(str.substring(0,str.length()-1)); }elseif(input.equals("CE")||input.equals("C")){ displayField.setText("0"); start=true; }else displayField.setText(displayField.getText()+input); } } } privateclassCommandActionimplementsActionListener{ publicvoidactionPerformed(ActionEventevt){ Stringcommand=evt.getActionCommand(); if(start){ lastCommand=command; }else{ calculate(Double.parseDouble(displayField.getText())); lastCommand=command; start=true; } } } publicvoidcalculate(doublex){ if(lastCommand.equals("+")) result+=x; elseif(lastCommand.equals("-")) result-=x; elseif(lastCommand.equals("*")) result*=x; elseif(lastCommand.equals("/")) result/=x; elseif(lastCommand.equals("=")) result=x; displayField.setText(""+result); } publicstaticvoidmain(String[]args){ Calculatorcalculator=newCalculator(); calculator.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } }
方法二:
importjava.awt.*; importjava.awt.event.*; publicclassMyCalculator{ PRivateFramef; privateTextFieldtf=newTextField(30); privatelongresult; privatebooleanappend=false; privatecharOperator='='; privateButton[]btn=newButton[15]; publicMyCalculator(){ initComponent(); } privatevoidinitComponent(){ f=newFrame("MyCalculatorV1.0"); f.setLayout(newBorderLayout());//TheframeusesBorderLayout f.addWindowListener(newWindowAdapter(){ publicvoidwindowClosing(WindowEventevt){ System.exit(0); } }); PanelcenterPanel=newPanel(); centerPanel.setLayout(newGridLayout(5,3));//ThepanelusesGridLayout NumberListenernl=newNumberListener(); OperatorListenerol=newOperatorListener(); btn[10]=newButton("+"); btn[11]=newButton("-"); btn[12]=newButton("*"); btn[13]=newButton("/"); btn[14]=newButton("="); for(inti=0;i<=9;i++){ btn[i]=newButton(String.valueOf(i)); centerPanel.add(btn[i]); btn[i].addActionListener(nl); if(i%2==1){ centerPanel.add(btn[(i+19)/2]); btn[(i+19)/2].addActionListener(ol); } } f.add(centerPanel,BorderLayout.CENTER); PanelnorthPanel=newPanel(); tf.setEditable(false); northPanel.add(tf); f.add(northPanel,BorderLayout.NORTH); } publicvoidgo(){ f.pack(); f.setVisible(true); } publicstaticvoidmain(String[]args){ newMyCalculator().go(); } /** *采用成员内部类方式,实现监听器接口,方便访问主类内类内部成员。 *此类负责数字按钮Action事件监听和处理 */ classNumberListenerimplementsActionListener{ publicvoidactionPerformed(ActionEvente){ if(!append){ tf.setText(""); append=true; } Strings=tf.getText(); s+=e.getActionCommand(); tf.setText(s); if(!btn[10].isEnabled()){ for(inti=10;i<=14;i++)btn[i].setEnabled(true); } } } /** *成员内部类,负责操作符按钮的事件处理 */ classOperatorListenerimplementsActionListener{ publicvoidactionPerformed(ActionEvente){ if(!append)return; for(inti=10;i<=14;i++)btn[i].setEnabled(false); Strings=tf.getText(); longnum=Long.parseLong(s);//getthenumberoftextfield append=false;//setappend switch(operator){ case'+':result+=num;break; case'-':result-=num;break; case'*':result*=num;break; case'/':{ if(num==0)result=0; elseresult/=num; break; } case'=':result=num;break; } tf.setText(String.valueOf(result)); //setthevalueofresulttotextfield Stringop=e.getActionCommand(); operator=op.charAt(0);//setoperator } } }
方法三:
packagewanwa; importjava.util.*; publicclasscalc{ publicstaticvoidmain(String[]args){ Scannerinput=newScanner(System.in); System.out.println("*****************简易计算器****************"); System.out.println("*\t\t\t\t\t*"); System.out.println("*使用说明:1.加法2.减法3.乘法4.除法*"); System.out.println("*\t\t\t\t\t*"); System.out.println("*****************************************"); for(inti=0;i<100;i++){ System.out.print("\n请选择运算规则:"); intnum=input.nextInt(); switch(num){ case1: System.out.println("\n******你选择了加法******\n"); System.out.print("请输入第1个加数:"); intjiashu1=input.nextInt(); System.out.print("请输入第2个加数:"); intjiashu2=input.nextInt(); System.out.println("运算结果为:"+jiashu1+"+"+jiashu1+"="+(jiashu1+jiashu2)); break; case2: System.out.println("\n******你选择了减法******\n"); System.out.print("请输入被减数:"); intjianshu1=input.nextInt(); System.out.print("请输入减数:"); intjianshu2=input.nextInt(); System.out.println("运算结果为:"+jianshu1+"-"+jianshu2+"="+(jianshu1-jianshu2)); break; case3: System.out.println("\n******你选择了乘法******\n"); System.out.print("请输入第1个因数:"); intchengfa1=input.nextInt(); System.out.print("请输入第2个因数:"); intchengfa2=input.nextInt(); System.out.println("运算结果为:"+chengfa1+"*"+chengfa2+"="+(chengfa1*chengfa2)); break; case4: System.out.println("\n******你选择了除法******\n"); System.out.print("请输入被除数:"); doublechufa1=input.nextInt(); System.out.print("请输入除数:"); doublechufa2=input.nextInt(); System.out.println("运算结果为:"+chufa1+"/"+chufa2+"="+(chufa1/chufa2)+"余"+(chufa1%chufa2)); break; default: System.out.println("\n你的选择有错,请重新选择!"); break; } } } }
方法四:
packagewanwa; importjava.awt.*; importjava.awt.event.*; importjavax.swing.*; publicclassCalculatorextendsJFrame{ privateContainercontainer; privateGridBagLayoutlayout; privateGridBagConstraintsconstraints; privateJTextFielddisplayField;//计算结果显示区 privateStringlastCommand;//保存+,-,*,/,=命令 privatedoubleresult;//保存计算结果 privatebooleanstart;//判断是否为数字的开始 publicCalculator(){ super("Calculator"); container=getContentPane(); layout=newGridBagLayout(); container.setLayout(layout); constraints=newGridBagConstraints(); start=true; result=0; lastCommand="="; displayField=newJTextField(20); displayField.setHorizontalAlignment(JTextField.RIGHT); constraints.gridx=0; constraints.gridy=0; constraints.gridwidth=4; constraints.gridheight=1; constraints.fill=GridBagConstraints.BOTH; constraints.weightx=100; constraints.weighty=100; layout.setConstraints(displayField,constraints); container.add(displayField); ActionListenerinsert=newInsertAction(); ActionListenercommand=newCommandAction(); //addButton("Backspace",0,1,2,1,insert); //addButton("CE",2,1,1,1,insert); //addButton("C",3,1,1,1,insert); addButton("7",0,2,1,1,insert); addButton("8",1,2,1,1,insert); addButton("9",2,2,1,1,insert); addButton("/",3,2,1,1,command); addButton("4",0,3,1,1,insert); addButton("5",1,3,1,1,insert); addButton("6",2,3,1,1,insert); addButton("*",3,3,1,1,command); addButton("1",0,4,1,1,insert); addButton("2",1,4,1,1,insert); addButton("3",2,4,1,1,insert); addButton("-",3,4,1,1,command); addButton("0",0,5,1,1,insert); //addButton("+/-",1,5,1,1,insert);//只显示"-"号,"+"没有实用价值 addButton(".",2,5,1,1,insert); addButton("+",3,5,1,1,command); addButton("=",0,6,4,1,command); this.setResizable(false); setSize(180,200); setVisible(true); } privatevoidaddButton(Stringlabel,introw,intcolumn,intwith, intheight,ActionListenerlistener){ JButtonbutton=newJButton(label); constraints.gridx=row; constraints.gridy=column; constraints.gridwidth=with; constraints.gridheight=height; constraints.fill=GridBagConstraints.BOTH; button.addActionListener(listener); layout.setConstraints(button,constraints); container.add(button); } privateclassInsertActionimplementsActionListener{ publicvoidactionPerformed(ActionEventevent){ Stringinput=event.getActionCommand(); if(start){ displayField.setText(""); start=false; if(input.equals("+/-")) displayField.setText(displayField.getText()+"-"); } if(!input.equals("+/-")){ if(input.equals("Backspace")){ Stringstr=displayField.getText(); if(str.length()>0) displayField.setText(str.substring(0,str.length()-1)); }elseif(input.equals("CE")||input.equals("C")){ displayField.setText("0"); start=true; }else displayField.setText(displayField.getText()+input); } } } privateclassCommandActionimplementsActionListener{ publicvoidactionPerformed(ActionEventevt){ Stringcommand=evt.getActionCommand(); if(start){ lastCommand=command; }else{ calculate(Double.parseDouble(displayField.getText())); lastCommand=command; start=true; } } } publicvoidcalculate(doublex){ if(lastCommand.equals("+")) result+=x; elseif(lastCommand.equals("-")) result-=x; elseif(lastCommand.equals("*")) result*=x; elseif(lastCommand.equals("/")) result/=x; elseif(lastCommand.equals("=")) result=x; displayField.setText(""+result); } publicstaticvoidmain(String[]args){ Calculatorcalculator=newCalculator(); calculator.setDefaultCloSEOperation(JFrame.EXIT_ON_CLOSE); } }
希望本文所述对大家Java程序设计有所帮助。