分享一个java写的简单计算器

来源:互联网 发布:我打打单软件 编辑:程序博客网 时间:2024/06/10 07:13

        一个简单的计算器,只实现了加、减、乘、除等简单功能,界面如下所示

计算器界面

   原代码如下:

package UI;//计算器import java.awt.BorderLayout;import java.awt.GridLayout;import javax.swing.*;import java.awt.event.*;import javax.swing.JTextField;public class Calculator1 implements ActionListener{private JButton jb=new JButton();//按钮private JTextField jtf=new JTextField();//窗体private String oldString="0";//记录老数据private String newString="0";//记录新数据private String operater="";//记录运算符private int count1=0;//等号的数量private int count2=0;//运算符的数量private boolean append=true;//在操作数据时用于判断追加或替换private boolean m=true;private boolean n=true;public Calculator1(){JFrame jf=new JFrame("计算器");jf.setResizable(false);BorderLayout border=new BorderLayout();jtf.setEditable(false);jf.add(jtf,BorderLayout.NORTH);JPanel jp=new JPanel();GridLayout gl=new GridLayout(5,4);jp.setLayout(gl);String[] str={"Backs","CE","C","+","7","8","9","-","4","5","6","*","1","2","3","/","0",".","+/-","="};for(int i=0;i<str.length;i++){//布局按钮jb=new JButton(str[i]);jb.addActionListener(this);//给每个按钮注册监听jp.add(jb);}jf.add(jp);jf.pack();//自动调整窗口大小jf.setLocation(300, 200);//显示位置jf.setVisible(true);//可以显示jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//关闭后停止工作}public void actionPerformed(ActionEvent e) {String com=e.getActionCommand();if(com.matches("^\\d$")){if(append&&m){String text=jtf.getText();jtf.setText(text+com);}else if(!append&&m){jtf.setText(com);append=true;}}else if("+-*/".indexOf(com)!=-1){count2++;append=false;if(count1==0&&count2>1){newString=jtf.getText();double d1=Double.parseDouble(oldString);double d2=Double.parseDouble(newString);double d=0;if(operater.matches("\\+")){d=d1+d2;}else if(operater.matches("\\-")){d=d1-d2;}else if(operater.matches("\\*")){d=d1*d2;}else{if(d2==0){jtf.setText("除数不能为零");m=false;}else{d=d1/d2;}}if(m){jtf.setText(d+"");}append=false;}count1=0;oldString=jtf.getText();operater=com;}else if(com.matches("^=$")){count1++;count2=0;newString=jtf.getText();double d1=Double.parseDouble(oldString);double d2=Double.parseDouble(newString);double d=0;if(operater.matches("\\+")){d=d1+d2;}else if(operater.matches("\\-")){d=d1-d2;}else if(operater.matches("\\*")){d=d1*d2;}else{if(d2==0){jtf.setText("除数不能为零");m=false;}else{d=d1/d2;}}if(m){jtf.setText(d+"");}append=false;}else if(".".equals(com)){String temp=jtf.getText();if(temp.indexOf(".")==-1){jtf.setText(temp+".");append=true;}}else if("+/-".equals(com)){String temp=jtf.getText();if(temp.startsWith("-")){jtf.setText(temp.substring(1));}else{jtf.setText("-"+temp);}}else if("C".equals(com)){jtf.setText("0");newString="0";oldString="0";count1=0;count2=0;append=false;m=true;}else if("CE".equals(com)){newString="0";jtf.setText(oldString);append=false;m=true;}else if("Backs".equals(com)){String temp=jtf.getText();char[] c=temp.toCharArray();jtf.setText(temp.substring(0,c.length-1));}}public static void main(String[] args) {Calculator1 c=new Calculator1();}}


原创粉丝点击