用JAVA编写计算器程序(模拟Windows计算器)

合集下载

用java代码写的简易计算器(可以实现基本的加减乘除功能)

用java代码写的简易计算器(可以实现基本的加减乘除功能)

⽤java代码写的简易计算器(可以实现基本的加减乘除功能)package A;import java.awt.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.MouseEvent;import java.awt.event.MouseListener;import javax.swing.*;public class Calcular3 extends JFrame implements ActionListener,MouseListener{private int m1=0,n=0;//private double m2=0;//运算的数private int flag=0;JFrame f;JPanel p1,p2,p3;JTextField t;JButton b1[]=new JButton[18];String b[]= {"1","2","3","4","5","6","7","8","9","0","清空","退格",".","=","+","-","*","/"};public Calcular3(){f=new JFrame("计算器");t=new JTextField(35);p1=new JPanel();p2=new JPanel();p3=new JPanel();f.setBounds(100, 100, 400, 200);f.add(p1,BorderLayout.NORTH);f.add(p2,BorderLayout.CENTER);f.add(p3,BorderLayout.EAST);p2.setLayout(new GridLayout(5,3));p3.setLayout(new GridLayout(4,1));p1.add(t);for(int i=0;i<14;i++) {b1[i]=new JButton(b[i]);p2.add(b1[i]);b1[i].addActionListener(this);}for(int i=14;i<18;i++) {b1[i]=new JButton(b[i]);p3.add(b1[i]);b1[i].addActionListener(this);}/*for(int i=0;i<18;i++) {b1[i].addActionListener(this);}*/f.setVisible(true);}//实现接⼝的⽅法public void mouseClicked(MouseEvent e) {}public void mousePressed(MouseEvent e) {}public void mouseReleased(MouseEvent e) {}public void mouseEntered(MouseEvent e) {}public void mouseExited(MouseEvent e) {}public void actionPerformed(ActionEvent e) {String str="";int i;for(i=0;i<=9;i++) {if(e.getSource()==b1[i]) {if(i==9) {n=n*10;}else {n=n*10+i+1;}str=String.valueOf(n);//整形n转换成字符串strt.setText(str);//显⽰到⽂本框上}}for(i=14;i<18;i++) {//+、-、*、/if(e.getSource()==b1[i]) {//匹配运算符m1=Integer.parseInt(t.getText());if(flag==15) {m2=m1+m2;}else if(flag==16) {m2=m1-m2;}else if(flag==17) {m2=m1*m2;}else if(flag==18) {m2=m1/m2;}else m2=m1;//若⽆连续的运算符运算,保存当前数据到m2 if(i==14) flag=15;else if(i==15) flag=16;else if(i==16) flag=17;else flag=18;str=String.valueOf(b[i]);t.setText(str);//显⽰到⽂本框上n=0;//还原,记录下次数据break;//找到匹配数据退出循环}}if(e.getSource()==b1[13]) {//=m1=Integer.parseInt(t.getText());if(flag==15) {m2=m2+m1;}else if(flag==16) {m2=m2-m1;}else if(flag==17) {m2=m2*m1;}else if(flag==18) {m2=m2/m1;}else m2=m1;str=String.valueOf(m2);t.setText(str);//显⽰到⽂本框上n=0;//还原,记录下次数据flag=0;//flag还原0,表明没有未处理的运算符}if(e.getSource()==b1[10]) {//各变量变为0 清空m1=0;m2=0;flag=0;n=0;t.setText("0");//显⽰到⽂本框上}if(e.getSource()==b1[11]) {//退格m1=(int)(Double.parseDouble(t.getText())/10);n=m1;str=String.valueOf(m1);t.setText(str);}if(e.getSource()==b1[12]) {//⼩数点m1=Integer.parseInt(t.getText());str=String.valueOf(m1+b[12]);t.setText(str);//显⽰到⽂本框上int j=0;for(i=0;i<=9;i++) {if(e.getSource()==b1[i]) {j++;m2=Math.pow(0.1, j)*Integer.parseInt(b[i]);str=String.valueOf(m1+m2);t.setText(str);//显⽰到⽂本框上}}}}//主函数public static void main(String[] args) {new Calcular3();}}。

【建立】java编写简单计算器

【建立】java编写简单计算器

【关键字】建立今天闲着没事,用java写了一个简单计算器,能实现简单的数据计算。

语言:java开发环境:eclipse(因为是按自己的想法写的,所以有些不尽人意的地方请谅解,希望对初学java者有些许帮助,有不好理解的地方,我尽量注释,有不理解的可以在百度HI我)事先一定要安装好JDK,可以在下载,配置好环境变量,再安装好eclipse,也可以在网上下载到,具体自己去找;然后打开eclipse建立一个工程,取名随便,我这里取名Calculator;然后在建立好的工程里面新建两个包,报名也自己取,尽量易懂,容易让人理解;我这里建立了两个包,Client 和UI,等下在Client里面放的是主函数,UI里面放的是界面文件和控制器;好了下面开始写代码;一、先写界面代码:在UI包里面新建一个Class文件,取名自己想,这里我写的是CalculatorFramepackage ui;import ;import ;import ;import ;import ;import ;import ;import ;import ;import ;import ;import ;public class CalculatorFrame extends JFrame {private static final long serialVersionUID = 1L;public String opt;public String str;private JTextArea show;private ClientContext clientContext;//引用控制器东西/*因为调用了控制器里面的方法,所以要对控制器的东西进行赋值,否则运行会出现空指针异常*/public void setClientContext(ClientContext clientContext) {this.clientContext = clientContext;}public CalculatorFrame() {init();}private void init() {setTitle(" Simple Calculator");setBounds(533, 184, 300, 400);setContentPane(creatContentPane());}private JPanel creatContentPane() {JPanel p = new JPanel(new GridLayout(4, 1)); /* 在面板里面添加4个面板*/p.add(showPane());//显示屏p.add(btnPane1());//下面三个都是按钮p.add(btnPane2());p.add(btnPane3());return p;}/*实现各个面板*/private JScrollPane showPane() {JScrollPane p = new JScrollPane();p.setBorder(new TitledBorder("Display:"));show = new JTextArea();show.setFont(new Font("",Font.PLAIN,25));show.setForeground(Color.RED);show.setLineWrap(true);show.setEditable(false);p.getViewport().add(show);return p;}private JPanel btnPane1() {JPanel p = new JPanel(new GridLayout(2, 4));JButton add = new JButton("+");JButton jian = new JButton("-");JButton cheng = new JButton("*");JButton chu = new JButton("/");JButton one = new JButton("1");JButton two = new JButton("2");JButton three = new JButton("3");JButton anser = new JButton("=");p.add(add);p.add(jian);p.add(cheng);p.add(chu);p.add(one);p.add(two);p.add(three);p.add(anser);/*用内部类实现按钮监视器,后面的都是这样*/one.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent arg0) {String number = show.getText() + String.valueOf(1);//按了数字“1”按//钮后,操作显示屏,既更新一下显示屏clientContext.setNumber(number);//调用控制器里面的方法}});two.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent arg0) {String number = show.getText() + String.valueOf(2);;clientContext.setNumber(number);}});three.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stubString number = show.getText() + String.valueOf(3);clientContext.setNumber(number);}});add.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent arg0) {opt = "+";clientContext.setOpt(opt);}});jian.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stubopt = "-";clientContext.setOpt(opt);}});cheng.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stubopt = "*";clientContext.setOpt(opt);}});chu.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stubopt = "/";clientContext.setOpt(opt);}});anser.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent arg0) { str = "=";clientContext.setAnswer(str);}});return p;}private JPanel btnPane2() {JPanel p = new JPanel(new GridLayout(2, 4));JButton four = new JButton("4");JButton five = new JButton("5");JButton six = new JButton("6");JButton pi = new JButton("PI");JButton seven = new JButton("7");JButton eight = new JButton("8");JButton nine = new JButton("9");JButton com = new JButton(".");p.add(four);p.add(five);p.add(six);p.add(pi);p.add(seven);p.add(eight);p.add(nine);p.add(com);four.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stubString number = show.getText() + String.valueOf(4);clientContext.setNumber(number);}});five.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stubString number = show.getText() + String.valueOf(5);clientContext.setNumber(number);}});six.addActionListener(new ActionListener() {@Override// TODO Auto-generated method stubString number = show.getText() + String.valueOf(6);clientContext.setNumber(number);}});seven.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stubString number = show.getText() + String.valueOf(7);clientContext.setNumber(number);}});eight.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stubString number = show.getText() + String.valueOf(8);clientContext.setNumber(number);}});nine.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stubString number = show.getText() + String.valueOf(9);clientContext.setNumber(number);}});com.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stubsetShow(show.getText() + ".");}});pi.addActionListener(new ActionListener() {@Override// TODO Auto-generated method stubsetShow(String.valueOf(Math.PI));}});return p;}private JPanel btnPane3() {JPanel p = new JPanel(new GridLayout(2, 4));JButton zero = new JButton("0");JButton sqrt = new JButton("√");JButton guiling = new JButton("C");final JButton help = new JButton("Help");p.add(zero);p.add(sqrt);p.add(guiling);p.add(help);help.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stubJOptionPane.showMessageDialog(help, "注意:假如第二运算数为空的话,这里将默认为0.0!");}});guiling.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stubclientContext.setMc();}});zero.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stubString number = show.getText() + String.valueOf(0);clientContext.setNumber(number);}});sqrt.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stubsetShow("" + Math.sqrt(getShow()));}});return p;}/*更新计算器的显示屏*/public void setShow(String str) {show.setText(str);}/*获取当前显示屏里面的数据*/public Double getShow() {String str = show.getText();if (str.equals("")) {str = "0.0";}return Double.valueOf(str);}/*获取当前选择的运算符:比如加或减或乘或除*/public String getOpt() {return this.opt;}}二、写控制器代码在UI包建立一个Class,我取名ClientContextpackage ui;import ;import ;import ;public class ClientContext {private CalculatorFrame calculatorFrame;private Double first = 0.0;private Double next = 0.0;public void setCalculatorFrame(CalculatorFrame calculatorFrame) {this.calculatorFrame = calculatorFrame;}double sum = 0;public void setNumber(String str) {calculatorFrame.setShow(str);}public void setOpt(String opt) {first = calculatorFrame.getShow();calculatorFrame.setShow("");}public void setAnswer(String str) {//按了“=”后,对数据按运算符进行计算next = calculatorFrame.getShow();// calculatorFrame.setShow(str);// switch(str){//// }if (calculatorFrame.getOpt() == "+") {double answer = first + next;calculatorFrame.setShow(String.valueOf(answer));} else if (calculatorFrame.getOpt() == "-") {double answer = first - next;calculatorFrame.setShow(String.valueOf(answer));} else if (calculatorFrame.getOpt() == "*") {double answer = first * next;calculatorFrame.setShow(String.valueOf(answer));} else if (calculatorFrame.getOpt() == "/") {if (next == 0) {calculatorFrame.setShow("对不起,除数不能为0");} else {double answer = first / next;calculatorFrame.setShow(String.valueOf(answer));}} else {calculatorFrame.setShow(String.valueOf(calculatorFrame.getShow()));}}public void setMc() {// TODO Auto-generated method stubcalculatorFrame.setShow("");first = 0.0;next = 0.0;calculatorFrame.opt=null;}}三、写主方法在Client包里面新建Class,我取名Mainpackage client;import ;import ui.CalculatorFrame;import ui.ClientContext;public class Main {/*** @param args*/public static void main(String[] args) {// TODO Auto-generated method stubCalculatorFrame c = new CalculatorFrame();c.setVisible(true);ClientContext clientContext = new ClientContext();c.setClientContext(clientContext);clientContext.setCalculatorFrame(c);}}最后运行后如下:文档来源为:从网络收集整理.word版本可编辑.欢迎下载支持.此文档是由网络收集并进行重新排版整理.word可编辑版本!11。

java计算器程序代码

java计算器程序代码

import java.awt.*;//计算器实例import java.awt.event.*;public class calculator{public static void main(String args[]){MyWindow my=new MyWindow("计算器");}}class MyWindow extends Frame implements ActionListener{ StringBuffer m=new StringBuffer();int p;TextField tex;Buttonb0,b1,b2,b3,b4,b5,b6,b7,b8,b9,jia,jian,cheng,chu,deng,dian,qingling,kaifang;MyWindow(String s){super(s);//StringBuffer s2=new StringBuffer();//String s;tex=new TextField(18);b0=new Button(" 0 ");b1=new Button(" 1 ");b2=new Button(" 2 ");b3=new Button(" 3 ");b4=new Button(" 4 ");b5=new Button(" 5 ");b6=new Button(" 6 ");b7=new Button(" 7 ");b8=new Button(" 8 ");b9=new Button(" 9 ");dian=new Button(" . ");jia=new Button(" + ");jian=new Button(" - ");cheng=new Button(" × ");chu=new Button(" / ");deng=new Button(" = ");qingling=new Button(" 清零 ");kaifang=new Button(" √ ");setLayout(new FlowLayout());add(tex);add(b0);add(b1);add(b2);add(b3);add(b4);add(b5);add(b6);add(b7);add(b8);add(b9);add(dian);add(jia);add(jian);add(cheng);add(chu);add(kaifang);add(qingling);add(deng);b0.addActionListener(this);b1.addActionListener(this);b2.addActionListener(this);b3.addActionListener(this);b4.addActionListener(this);b5.addActionListener(this);b6.addActionListener(this);b7.addActionListener(this);b8.addActionListener(this);b9.addActionListener(this);jia.addActionListener(this);jian.addActionListener(this);cheng.addActionListener(this);chu.addActionListener(this);dian.addActionListener(this);deng.addActionListener(this);qingling.addActionListener(this); kaifang.addActionListener(this);setBounds(200,200,160,280);setResizable(false);//不可改变大小setVisible(true);validate();addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent ee){ System.exit(0);}});}public void actionPerformed(ActionEvent e){if(e.getSource()==b0){m=m.append("0");tex.setText(String.valueOf(m));}if(e.getSource()==b1){m=m.append("1"); tex.setText(String.valueOf(m)); }if(e.getSource()==b2){m=m.append("2"); tex.setText(String.valueOf(m)); }if(e.getSource()==b3){m=m.append("3"); tex.setText(String.valueOf(m)); }if(e.getSource()==b4){m=m.append("4"); tex.setText(String.valueOf(m));}if(e.getSource()==b5){m=m.append("5"); tex.setText(String.valueOf(m)); }if(e.getSource()==b6){m=m.append("6"); tex.setText(String.valueOf(m)); }if(e.getSource()==b7){m=m.append("7"); tex.setText(String.valueOf(m)); }if(e.getSource()==b8){m=m.append("8"); tex.setText(String.valueOf(m)); }if(e.getSource()==b9){m=m.append("9"); tex.setText(String.valueOf(m)); }if(e.getSource()==jia){m=m.append("+"); tex.setText(String.valueOf(m)); }if(e.getSource()==jian){m=m.append("-"); tex.setText(String.valueOf(m)); }if(e.getSource()==cheng){m=m.append("*"); tex.setText(String.valueOf(m)); }if(e.getSource()==chu){m=m.append("/"); tex.setText(String.valueOf(m)); }if(e.getSource()==dian){m=m.append("."); tex.setText(String.valueOf(m)); }String mm=String.valueOf(m);int p1=mm.indexOf("+");int p2=mm.indexOf("-");int p3=mm.indexOf("*");int p4=mm.indexOf("/");if(p1!=-1){p=p1;}else if(p3!=-1){p=p3;}else if(p2!=-1){p=p2;}else if(p4!=-1){p=p4;}if(e.getSource()==deng){String m1=mm.substring(0,p);String m2=mm.substring(p+1);String ch=mm.substring(p,p+1);//System.out.println(m1);//System.out.println(m2);//System.out.println(ch);if(ch.equals("+")){float n1=Float.parseFloat(m1); float n2=Float.parseFloat(m2); float sum=n1+n2;String su=String.valueOf(sum); tex.setText(su);}if(ch.equals("-")){float n1=Float.parseFloat(m1);float n2=Float.parseFloat(m2);float sum=n1-n2;String su=String.valueOf(sum);tex.setText(su);}if(ch.equals("*")){float n1=Float.parseFloat(m1);float n2=Float.parseFloat(m2);float sum=n1*n2;String su=String.valueOf(sum);tex.setText(su);}if(ch.equals("/")){float n1=Float.parseFloat(m1);float n2=Float.parseFloat(m2);float sum=n1/n2;String su=String.valueOf(sum);tex.setText(su);}}if(e.getSource()==qingling){StringBuffer kk=new StringBuffer(); m=kk;tex.setText("0");// System.out.println(mm);}if(e.getSource()==kaifang){String t=tex.getText();float num=Float.parseFloat(t);double nub=Math.sqrt(num);tex.setText(String.valueOf(nub)); }}}。

Java实现简易计算器

Java实现简易计算器

Java实训作业题目:Java实现简易计算器学院:姓名:学号:班级:20 年月一、实验目的通过课程设计,主要要达到两个目的,一是检验和巩固专业知识、二是提高综合素质和能力。

此次课程设计实训主要是Java语言程序设计的实现。

通过该课程设计,可以将课堂上掌握的理论知识与处理数据的业务相结合,以检验自己掌握知识的宽度、深度及对知识的综合运用能力。

二、实验要求用Java编写一个简单的计算器,使其能够实现最基本的功能,如简单的加、减、乘、除;平方根,倒数,平方等功能。

三、详细内容1.界面设计界面设计使用GUI,其中有用到swing组件的TextField和Button,用到awt中的BorderLayout和GridLayout布局管理方式,其图形界面如图1-1所示:图1-1其中主要代码为:public mainWindow(){this.setTitle("计算器");//用户图形界面标题this.setVisible(true);//用户图形界面可缩小this.setResizable(false);//用户图形界面不可放大this.setSize(350,300);//设置用户图形界面的大小this.setLocation(400,150);//用户图形界面在屏幕中的显示位置JPanel panel1 = new JPanel();//新建一个画板JPanel panel2 = new JPanel();button1 = new JButton("1");...reset = new JButton("CE");Container container = this.getContentPane();container.add(panel2,BorderLayout.NORTH);container.add(panel1);panel1.setLayout(new GridLayout(5,4));//将画板1分为4行5列result.setEnabled(false);result.setFont(new Font("Dialog",Font.BOLD,25));//运算结果的字体大小result.setEditable(false);result.setHorizontalAlignment(SwingConstants.RIGHT);panel1.add(reciprocal);//分别将20个按钮依次添加到画板panel1中,并设置各自的大小reciprocal.setFont(new Font("Dialog",Font.PLAIN,20));...panel1.add(divide);divide.setFont(new Font("Dialog",Font.PLAIN,20));panel2.setLayout(new GridLayout());panel2.add(result);//画板panel2添加运算结果2.四则运算较为简单的实现了简单的加、减、乘、除运算,主要代码如下:ActionListener equal1 = new ActionListener(){ //实现四则运算public void actionPerformed(ActionEvent e){String str = result.getText();b = DatatypeConverter.parseDouble(str);{if(flag == "+")c = a + b;else if(flag == "-")c = a - b;else if(flag == "*")c = a * b;else if(flag == "/" || b != 0)c = a / b;}if(flag != "=")result.setText("" + c);elseresult.setText("零不能做除数!");a = 0;b = 0;c = 0;flag = "";}};3.其他功能另外添加了平方根,倒数,平方等功能,主要代码如下:平方根运算的实现:ActionListener sqrt1= new ActionListener(){public void actionPerformed(ActionEvent e){String str = result.getText();double i = DatatypeConverter.parseDouble(str);i = Math.sqrt(i);result.setText("" + i);}};倒数运算的实现:ActionListener reciprocal1 = new ActionListener(){ public void actionPerformed(ActionEvent e){String str = result.getText();double i = DatatypeConverter.parseDouble(str);i = 1/i;result.setText("" + i);}};平方运算的实现:ActionListener square1 = new ActionListener(){public void actionPerformed(ActionEvent e){String str = result.getText();double i = DatatypeConverter.parseDouble(str);i = i*i;result.setText("" + i);}};4.程序测试经测试发现本计算器基本功能均能实现,可正常运行计算,针对功能实现的代码部分过于简单,可以对其进行改善提高,方便用户使用!5.实训小结通过对计算器窗体的编写,熟悉了java图形用户界面的设计原理和程序结构,熟悉了java中awt和swing的组合。

java计算器源代码(仿win7)

java计算器源代码(仿win7)

java计算器源代码(仿win7)import java.awt.*;import javax.swing.*;import java.awt.event.*;class Cal extends JFrame implements ActionListener,MouseListener{JMenuBar menubar;JMenu menu_check,menu_edit,menu_help;JMenuItem menuitem_science,menuitem_check,menuitem_exit,menuitem_copy,menuitem_paste,menuitem1_copy,menuitem1_paste,menuitem_chelp,menuitem_about;JCheckBoxMenuItem menuitem_standard;JTextField ta1;int x,result2;double op1,op2,opall;private boolean end=false,flag=false,add=false,sub=false,cheng=false,chu=false,flagop2=false;JButton b_mc,b_mr,b_ms,b_mjia,b_mjian,b_tui,b_ce,b_c,b_jj,b_dui,b_7,b_8,b_9,b_chu,b_baifenhao,b_4,b_5,b_6,b_cheng,b_daoshu,b_1,b_2,b_3,b_jian,b_0,b_dian,b_jia,b_dengyu;JPanel p_all,p_button1,p_button2,p_txt,p1,p2,p3,p4,p5;private String str,resultstr;JPopupMenu popupmenu;Container con=this.getContentPane();Font font=new Font("微软雅黑",Font.PLAIN,12);Color color=new Color(120,220,120);Cal(String s){super(s);setSize(220,315);setResizable(false);setVisible(true);Dimension scr=Toolkit.getDefaultToolkit().getScreenSize();Dimension frm=this.getSize();setLocation((scr.width-frm.width)/2,(scr.height-frm.height)/2);Toolkit tk=Toolkit.getDefaultToolkit();//程序默认图标设置setIconImage(tk.createImage("D:\\sd.jpg"));setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//-----------------------------------------------------------------制作框架结构------------------------- //---------------------------------------菜单栏---------------------------menubar=new JMenuBar();menubar.setPreferredSize(new Dimension(frm.width,19));menu_check=new JMenu("查看(V)");menu_check.setFont(font);menu_check.setForeground(Color.black);menuitem_standard=new JCheckBoxMenuItem("标准型",true);menuitem_standard.setFont(font);menuitem_standard.setForeground(Color.black);menuitem_science=new JMenuItem("科学型");menuitem_science.setFont(font);menuitem_science.setForeground(Color.black);menuitem_check=new JMenuItem("查看分组");menuitem_check.setFont(font);menuitem_check.setForeground(Color.black);menuitem_exit=new JMenuItem("退出");menuitem_exit.setFont(font);menuitem_exit.setForeground(Color.black);menuitem_exit.addActionListener(this);menu_check.add(menuitem_standard);menu_check.add(menuitem_science);menu_check.addSeparator();menu_check.add(menuitem_check);menu_check.addSeparator();menu_check.add(menuitem_exit);menubar.add(menu_check);menu_edit=new JMenu("编辑(E)");menu_edit.setFont(font);menu_edit.setForeground(Color.black);menu_edit.setMnemonic(KeyEvent.VK_E);menuitem_copy=new JMenuItem("复制(C) ");menuitem_copy.setFont(font);menuitem_copy.setForeground(Color.black);menuitem_copy.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C,InputEvent.CTRL_M ASK));menuitem_copy.addActionListener(this);menuitem_paste=new JMenuItem("粘贴(P) ");menuitem_paste.setFont(font);menuitem_paste.setForeground(Color.black);menuitem_paste.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V,InputEvent.CTRL_M ASK));menuitem_paste.addActionListener(this);menu_edit.add(menuitem_copy);menu_edit.add(menuitem_paste);menubar.add(menu_edit);menu_help=new JMenu("帮助(H)");menu_help.setFont(font);menu_help.setForeground(Color.black);menuitem_chelp=new JMenuItem("查看帮助");menuitem_chelp.setFont(font);menuitem_chelp.setForeground(Color.black);menuitem_about=new JMenuItem("关于计算器");menuitem_about.setFont(font);menuitem_about.setForeground(Color.black);menuitem_about.addActionListener(this);menu_help.add(menuitem_chelp);menu_help.addSeparator();menu_help.add(menuitem_about);menubar.add(menu_help);setJMenuBar(menubar);//--------------------------------------文本框----------------------------------ta1=new JTextField("0");ta1.setFont(new Font("微软雅黑",Font.PLAIN,13));ta1.setEditable(false);//ta1.setOpaque(false);ta1.setHorizontalAlignment(JTextField.RIGHT);ta1.setPreferredSize(new Dimension((frm.width-26),45));ta1.addMouseListener(this);p_all=new JPanel();p_all.setPreferredSize(new Dimension((frm.width-6),250));//p_all.setBackground(color);p_all.setLayout(new FlowLayout(FlowLayout.CENTER,0,3));p_txt=new JPanel();p_txt.setPreferredSize(new Dimension((frm.width-6),53));p_txt.setLayout(new FlowLayout(FlowLayout.CENTER,0,7));p_txt.add(ta1);p_all.add(p_txt);con.add(p_all,BorderLayout.CENTER);//-------------------------------------按钮区----------------------------------p_button1=new JPanel();p_button1.setPreferredSize(new Dimension((frm.width-25),131)); p_button1.setLayout(new FlowLayout(FlowLayout.LEFT,0,3));p_all.add(p_button1);p1=new JPanel();p1.setPreferredSize(new Dimension((frm.width-25),127));p1.setLayout(new GridLayout(4,5,5,6));b_mc=new JButton("MC");b_mc.setFont(new Font("微软雅黑",Font.PLAIN,11));b_mc.setMargin(new Insets(0,0,0,0));b_mc.setForeground(Color.blue);b_mc.addActionListener(this);b_mr=new JButton("MR");b_mr.setFont(new Font("微软雅黑",Font.PLAIN,11));b_mr.setMargin(new Insets(0,0,0,0));b_mr.setForeground(Color.blue);b_mr.addActionListener(this);b_ms=new JButton("MS");b_ms.setFont(new Font("微软雅黑",Font.PLAIN,11));b_ms.setMargin(new Insets(0,0,0,0));b_ms.setForeground(Color.blue);b_ms.addActionListener(this);b_mjia=new JButton("M+");b_mjia.setFont(new Font("微软雅黑",Font.PLAIN,11));b_mjia.setMargin(new Insets(0,0,0,0));b_mjia.setForeground(Color.blue);b_mjia.addActionListener(this);b_mjian=new JButton("M-");b_mjian.setFont(new Font("微软雅黑",Font.PLAIN,11)); b_mjian.setMargin(new Insets(0,0,0,0));b_mjian.setForeground(Color.blue);b_mjian.addActionListener(this);b_tui=new JButton("←");b_tui.setFont(new Font("微软雅黑",Font.BOLD,14));b_tui.setMargin(new Insets(0,0,0,0));b_tui.addActionListener(this);b_tui.setForeground(Color.red);b_ce=new JButton("CE");b_ce.setFont(new Font("微软雅黑",Font.PLAIN,11));b_ce.setMargin(new Insets(0,0,0,0));b_ce.setForeground(Color.red);b_ce.addActionListener(this);b_c=new JButton("C");b_c.setFont(new Font("微软雅黑",Font.PLAIN,11));b_c.setMargin(new Insets(0,0,0,0));b_c.setForeground(Color.red);b_c.addActionListener(this);b_jj=new JButton("±");b_jj.setFont(new Font("微软雅黑",Font.PLAIN,14));b_jj.setMargin(new Insets(0,0,0,0));b_jj.setForeground(Color.red);b_jj.addActionListener(this);b_dui=new JButton("√");b_dui.setFont(new Font("微软雅黑",Font.PLAIN,11)); b_dui.setMargin(new Insets(0,0,0,0));b_dui.setForeground(Color.red);b_dui.addActionListener(this);b_7=new JButton("7");b_7.setFont(new Font("微软雅黑",Font.PLAIN,14));b_7.setMargin(new Insets(0,0,0,0));b_7.setForeground(Color.blue);b_7.setMnemonic(KeyEvent.VK_7);b_7.addActionListener(this);b_8=new JButton("8");b_8.setFont(new Font("微软雅黑",Font.PLAIN,14));b_8.setMargin(new Insets(0,0,0,0));b_8.setForeground(Color.blue);b_8.setMnemonic(KeyEvent.VK_8);b_8.addActionListener(this);b_9=new JButton("9");b_9.setMargin(new Insets(0,0,0,0));b_9.setForeground(Color.blue);b_9.setMnemonic(KeyEvent.VK_9);b_9.addActionListener(this);b_chu=new JButton("/");b_chu.setFont(new Font("微软雅黑",Font.PLAIN,14));b_chu.setMargin(new Insets(0,0,0,0));b_chu.setForeground(Color.red);b_chu.addActionListener(this);b_baifenhao=new JButton("%");b_baifenhao.setFont(new Font("微软雅黑",Font.PLAIN,11)); b_baifenhao.setMargin(new Insets(0,0,0,0));b_baifenhao.setForeground(Color.blue);b_baifenhao.addActionListener(this);b_4=new JButton("4");b_4.setFont(new Font("微软雅黑",Font.PLAIN,14));b_4.setMargin(new Insets(0,0,0,0));b_4.setForeground(Color.blue);b_4.setMnemonic(KeyEvent.VK_4);b_4.addActionListener(this);b_5=new JButton("5");b_5.setFont(new Font("微软雅黑",Font.PLAIN,14));b_5.setMargin(new Insets(0,0,0,0));b_5.setForeground(Color.blue);b_5.setMnemonic(KeyEvent.VK_5);b_5.addActionListener(this);b_6=new JButton("6");b_6.setFont(new Font("微软雅黑",Font.PLAIN,14));b_6.setMargin(new Insets(0,0,0,0));b_6.setForeground(Color.blue);b_6.setMnemonic(KeyEvent.VK_6);b_6.addActionListener(this);b_cheng=new JButton("*");b_cheng.setFont(new Font("微软雅黑",Font.PLAIN,14));b_cheng.setMargin(new Insets(0,0,0,0));b_cheng.setForeground(Color.red);b_cheng.addActionListener(this);b_daoshu=new JButton("1/x");b_daoshu.setFont(new Font("微软雅黑",Font.PLAIN,11)); b_daoshu.setMargin(new Insets(0,0,0,0));b_daoshu.setForeground(Color.blue);b_daoshu.addActionListener(this);b_1=new JButton("1");b_1.setMargin(new Insets(0,0,0,0));b_1.setForeground(Color.blue);b_1.setMnemonic(KeyEvent.VK_1);b_1.addActionListener(this);b_2=new JButton("2");b_2.setFont(new Font("微软雅黑",Font.PLAIN,14)); b_2.setMargin(new Insets(0,0,0,0));b_2.setForeground(Color.blue);b_2.setMnemonic(KeyEvent.VK_2);b_2.addActionListener(this);b_3=new JButton("3");b_3.setFont(new Font("微软雅黑",Font.PLAIN,14)); b_3.setMargin(new Insets(0,0,0,0));b_3.setForeground(Color.blue);b_3.setMnemonic(KeyEvent.VK_3);b_3.addActionListener(this);b_jian=new JButton("-");b_jian.setFont(new Font("微软雅黑",Font.PLAIN,14)); b_jian.setMargin(new Insets(0,0,0,0));b_jian.setForeground(Color.red);b_jian.addActionListener(this);b_0=new JButton("0");b_0.setFont(new Font("微软雅黑",Font.PLAIN,14)); b_0.setMargin(new Insets(0,0,0,0));b_0.setPreferredSize(new Dimension(75,27));b_0.setForeground(Color.blue);b_0.setMnemonic(KeyEvent.VK_0);b_0.addActionListener(this);JLabel L1=new JLabel();L1.setPreferredSize(new Dimension(5,3));b_dian=new JButton(".");b_dian.setFont(new Font("微软雅黑",Font.BOLD,14)); b_dian.setMargin(new Insets(0,0,0,0));b_dian.setPreferredSize(new Dimension(35,27));b_dian.setForeground(Color.blue);b_dian.addActionListener(this);JLabel L2=new JLabel();L2.setPreferredSize(new Dimension(5,3));b_jia=new JButton("+");b_jia.setFont(new Font("微软雅黑",Font.BOLD,14)); b_jia.setMargin(new Insets(0,0,0,0));b_jia.setPreferredSize(new Dimension(35,27));b_jia.setForeground(Color.red);b_jia.addActionListener(this);b_dengyu=new JButton("=");b_dengyu.setFont(new Font("微软雅黑",Font.BOLD,22));b_dengyu.setMargin(new Insets(0,0,0,0));b_dengyu.setPreferredSize(new Dimension(35,60));b_dengyu.setForeground(Color.blue);b_dengyu.addActionListener(this);p1.add(b_mc);p1.add(b_mr);p1.add(b_ms);p1.add(b_mjia);p1.add(b_mjian);p1.add(b_tui);p1.add(b_ce);p1.add(b_c);p1.add(b_jj);p1.add(b_dui);p1.add(b_7);p1.add(b_8);p1.add(b_9);p1.add(b_chu);p1.add(b_baifenhao);p1.add(b_4);p1.add(b_5);p1.add(b_6);p1.add(b_cheng);p1.add(b_daoshu);p_button1.add(p1);p_button2=new JPanel();p_button2.setPreferredSize(new Dimension((frm.width-24),65)); p_button2.setLayout(new FlowLayout(FlowLayout.LEFT,0,0));p_all.add(p_button2);p2=new JPanel();p2.setPreferredSize(new Dimension(156,65));p2.setLayout(new FlowLayout(FlowLayout.LEFT,0,1));p3=new JPanel();p3.setPreferredSize(new Dimension(39,62));p3.setLayout(new FlowLayout(FlowLayout.LEFT,4,0));p_button2.add(p2);p_button2.add(p3);p4=new JPanel();p4.setPreferredSize(new Dimension(156,27));p4.setLayout(new GridLayout(1,4,5,5));p5=new JPanel();p5.setPreferredSize(new Dimension(156,39));p5.setLayout(new FlowLayout(FlowLayout.LEFT,0,5));p2.add(p4);p2.add(p5);p4.add(b_1);p4.add(b_2);p4.add(b_3);p4.add(b_jian);p5.add(b_0);p5.add(L1);p5.add(b_dian);p5.add(L2);p5.add(b_jia);p3.add(b_dengyu);//---------------------------------------快捷菜单对象-------------------------popupmenu=new JPopupMenu(); //快捷菜单对象menuitem1_copy=new JMenuItem("复制");menuitem1_copy.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C,InputEvent.CTRL_ MASK));menuitem1_copy.addActionListener(this); //监视鼠标右击菜单”复制“popupmenu.add(menuitem1_copy);menuitem1_paste=new JMenuItem("粘贴");menuitem1_paste.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V,InputEvent.CTRL_MASK));menuitem1_paste.addActionListener(this); //监视鼠标右击菜单”粘贴“popupmenu.add(menuitem1_paste);ta1.add(popupmenu);con.validate();validate();}//---------------------------------------功能区------------------------------------public void actionPerformed(ActionEvent e){if(e.getSource()==menuitem_about){JOptionPane.showMessageDialog(null,"这是一个模仿win7的计算器!欢迎改进,\n创作者:钟作明","仿win7计算器",RMATION_MESSAGE);}if(e.getSource()==menuitem1_copy){ta1.selectAll();ta1.copy();}else if(e.getSource()==menuitem1_paste){ta1.setEditable(true);ta1.setText("");ta1.paste();ta1.setEditable(false);}else if(e.getSource()==menuitem_copy){ta1.selectAll();ta1.copy();}else if(e.getSource()==menuitem_paste){ta1.setEditable(true);ta1.setText("");ta1.paste();ta1.setEditable(false);}else if(e.getSource()==menuitem_exit){System.exit(0);}else if(e.getSource()==b_ce){ta1.setEditable(true);ta1.setText("0");ta1.setEditable(false);}else if(e.getSource()==b_c){ta1.setEditable(true);ta1.setText("0");ta1.setEditable(false);}else if(e.getSource()==b_tui){String str=ta1.getText();StringBuffer s=new StringBuffer(str);int L=s.length();try{if(L!=1){s=s.deleteCharAt(L-1);}else{s=new StringBuffer("0");}}catch(Exception e1){}ta1.setText(String.valueOf(s));}//---------------------------------------------数字键----------------------------- if(e.getSource()==b_1){addString(1);}else if(e.getSource()==b_2){addString(2);}else if(e.getSource()==b_3){addString(3);}else if(e.getSource()==b_4){addString(4);}else if(e.getSource()==b_5){addString(5);}else if(e.getSource()==b_6){addString(6);}else if(e.getSource()==b_7){addString(7);}else if(e.getSource()==b_8){addString(8);}else if(e.getSource()==b_9){addString(9);}else if(e.getSource()==b_0){addString(0);}else if(e.getSource()==b_dian){StringBuffer s1=new StringBuffer(ta1.getText());StringBuffer dian=new StringBuffer(".");if(String.valueOf(s1).indexOf(".")==-1){s1.append(dian);}ta1.setText(String.valueOf(s1));}else if(e.getSource()==b_jj){String txt=ta1.getText();int result=Integer.parseInt(txt);if(txt.indexOf("-")==-1&&txt.length()>0){if(result!=0){txt="-"+txt;}}else{StringBuffer txt1=new StringBuffer(txt);txt1=txt1.deleteCharAt(0);txt=String.valueOf(txt1);}ta1.setText(txt);}else if(e.getSource()==b_dui){str=ta1.getText();Double d=Double.parseDouble(str);if(d>=0){double d1=Math.sqrt(d);String s = String.valueOf(d1);if(s.endsWith(".0")==true){int z=(int)d1;str=String.valueOf(z);}else{str=String.valueOf(d1);}ta1.setText(str);}else{JOptionPane.showMessageDialog(null,"根号底数不能为负数","提醒", RMATION_MESSAGE);}end=true;}else if(e.getSource()==b_baifenhao){str=ta1.getText();Double d=Double.parseDouble(str);ta1.setText(""+d/100);end=true;}else if(e.getSource()==b_daoshu){str=ta1.getText();Double d=Double.parseDouble(str);if(d!=0){ta1.setText(""+1/d);}else{JOptionPane.showMessageDialog(null,"除数不能为零","提醒", RMATION_MESSAGE);}end=true;}else if(e.getSource()==b_jia){str = ta1.getText();op1 = Double.parseDouble(str);end=true;x=0;opall=op1;flagop2=false;}else if(e.getSource()==b_jian){str = ta1.getText();op1 = Double.parseDouble(str);end=true;x=1;opall=op1;flagop2=false;}else if(e.getSource()==b_cheng){str = ta1.getText();op1 = Double.parseDouble(str);end=true;x=2;opall=op1;flagop2=false;}else if(e.getSource()==b_chu){str = ta1.getText();op1 = Double.parseDouble(str);end=true;x=3;opall=op1;flagop2=false;}else if(e.getSource()==b_dengyu){str = ta1.getText();if(flagop2==false){op2 = Double.parseDouble(str);flagop2=true;}switch(x){case 0 :opall=opall+op2;String s=String.valueOf(opall);if(s.endsWith(".0")==true){result2=(int)opall;resultstr=String.valueOf(result2);}else{resultstr=String.valueOf(opall);}ta1.setText(resultstr);break;case 1 :opall=opall-op2;s=String.valueOf(opall);if(s.endsWith(".0")==true){result2=(int)opall;resultstr=String.valueOf(result2);}else{resultstr=String.valueOf(opall);}ta1.setText(resultstr);break;case 2 :opall=opall*op2;s=String.valueOf(opall);if(s.endsWith(".0")==true){result2=(int)opall;resultstr=String.valueOf(result2);}else{resultstr=String.valueOf(opall);}ta1.setText(resultstr);break;case 3 :opall=opall/op2;s=String.valueOf(opall);if(s.endsWith(".0")==true){result2=(int)opall;resultstr=String.valueOf(result2);}else{resultstr=String.valueOf(opall);}ta1.setText(resultstr);break;}end=true;}}public void addString(int num){String s=null;s=String.valueOf(num);//如果end==true;,那么屏幕清空if(end==true){ta1.setText("0");end=false;}if((ta1.getText()).equals("0")){ta1.setText(s);}else{if(ta1.getText().length()<21){str=ta1.getText()+s;ta1.setText(str);}}}public void mouseClicked(MouseEvent mec){if(mec.getModifiers()==mec.BUTTON3_MASK){popupmenu.show(ta1,mec.getX(),mec.getY());}}public void mousePressed(MouseEvent ms){}public void mouseReleased(MouseEvent md){}public void mouseEntered(MouseEvent ms){}public void mouseExited(MouseEvent mex){}public void mouseDragged(MouseEvent med){}}public class Calculator {public static void main(String[] args) {// TODO Auto-generated method stubCal jishuanji=new Cal("计算器");}}。

JavaSwing实现仿win7计算器

JavaSwing实现仿win7计算器

JavaSwing实现仿win7计算器⾸先说明此代码的界⾯布局基本上参考了:由于后⾯的运算符处理操作实在难以理解。

所以后⾯事件的处理是⾃⼰改写的,我觉得这样⽐较好理解。

/****/package myJavaSwing;import javax.swing.JFrame;import java.awt.event.ActionListener;import java.awt.event.ActionEvent;import javax.swing.JButton;import javax.swing.JTextField;import javax.swing.JPanel;import java.awt.GridLayout;import java.awt.Color;import java.awt.BorderLayout;import java.awt.Container;/*** @author 花花*简介:仿windows7计算器*由于M键设计到存储器暂不⽀持M键的功能**/public class Calculator extends JFrame implements ActionListener {//计算器的三个功能键名字private final String COMMAND[]= {"Backspace","CE","C"};//计算计算⾯板上的键名private final String CALCULATE[]= {"7","8","9","/","sqrt","4","5","6","*","%","1","2","3","-","1/x","0","+/-",".","+","="};//计算器上的M键名private final String M[]= {" ","MC","MR","MS","M+"};//定义三个功能按钮JButton commands[]=new JButton[COMMAND.length];//定义计算⾯板班的按钮JButton calculate[]=new JButton[CALCULATE.length];//定义M按钮JButton m[]=new JButton[M.length];//结果⽂本框JTextField resultText=new JTextField();//计算结果private double result=0;//⽂本框中之前是否有输⼊private Boolean preferExist=false;//操作符private String op="=";//是否按了操作符private Boolean operate=false;//中间值。

java实验报告——简单计算器的编写五篇范文

java实验报告——简单计算器的编写五篇范文

java实验报告——简单计算器的编写五篇范文第一篇:java实验报告——简单计算器的编写JAVA实验报告——简单计算器的编写班级:学号:姓名:一、实验目的1.掌握java图形用户界面(GUI)的设计原理和程序结构2.能设计复核问题要求的图形用户界面程序3.掌握常用组件的事件接口4.应用awt和swing组件进行应用程序设计二、实验条件1.计算机一台2.java软件开发环境三、实验步骤1、编写代码:mport java.awt.*;import java.awt.event.*;import javax.swing.*;public class JCalculator extends JFrame implements ActionListener {private static final long serialVersionUID =-***457Lprivate class WindowCloser extends WindowAdapter {public void windowClosing(WindowEvent we){System.exit(0);}}int i;private final String[] str = { “7”, “8”, “9”, “/”, “4”, “5”, “6”, “*”, “1”,“2”, “3”, “-”, “.”, “0”, “=”, “+” };JButton[] buttons = new JButton[str.length]; JButton reset = new JButton(“CE”); JTextField display = new JTextField(“0”);public JCalculator(){super(“Calculator”);JPanel panel1 = new JPanel(new GridLayout(4, 4)); for(i = 0;i < str.length;i++){buttons[i] = new JButton(str[i]);panel1.add(buttons[i]);}JPanel panel2 = new JPanel(new BorderLayout()); panel2.add(“Center”, display);panel2.add(“East”, reset);getContentPane().setLayout(new BorderLayout()); getContentPane().add(“North”, panel2); getContentPane().add(“Center”, panel1);for(i = 0;i < str.length;i++)buttons[i].addActionListener(this);reset.addActionListener(this);display.addActionListener(this); addWindowListener(new WindowCloser()); setSize(800, 800);setVisible(true);pack();}public void actionPerformed(ActionEvent e){ Object target = e.getSource();String label = e.getActionCommand();if(target == reset)handleReset();else if(“0123456789.”.indexOf(label)> 0)handleNumber(label);elsehandleOperator(label);}boolean isFirstDigit = true;public void handleNumber(String key){if(isFirstDigit)display.setText(key);else if((key.equals(“.”))&&(display.getText().indexOf(“.”)< 0))display.setText(display.getText()+ “.”);else if(!key.equals(“.”))display.setText(display.getText()+ key);isFirstDigit = false;}public void handleReset(){display.setText(“0”);isFirstDigit = true;operator = “=”;}double number = 0.0;String operator = “=”;public void handleOperator(String key){if(operator.equals(“+”))number += Double.valueOf(display.getText());else if(operator.equals(“-”))number-= Double.valueOf(display.getText());else if(operator.equals(“*”))number *= Double.valueOf(display.getText());else if(operator.equals(“/”))number /= Double.valueOf(display.getText());else if(operator.equals(“=”))number = Double.valueOf(display.getText());display.setText(String.valueOf(number));operator = key;isFirstDigit = true;}public static void main(String[] args){new JCalculator();} }2、运行结果,见截图计算测试:123+456=579结果正确,程序无误。

java计算器代码及实验报告

java计算器代码及实验报告

一、实验内容题目:1、设计一个计算器要求:1、使用layout进行布局,使界面更加友好2、实现整数的加减乘除运算(不考虑优先级)二、实验过程(这是实验报告极其重要的内容。

要抓住重点,可以从理论和实践两个方面考虑。

这部分要写明依据什么知识点以及使用方法进行实验以及实验步骤。

不要简单照抄实习指导,更不可写一大堆源代码)二、实验过程1、进行计算器界面的布局:a 、Panel的嵌套布局:主要设置了七个Panel来将界面分成几个部分。

且Panel都是用borderLayout来进行的布局。

如图所示,其中4、5、6、7分别表示Panel4、Panel5、Panel6、Panel7Panel2由Panel4、Panel5组成;Panel3由Panel6、Panel7组成;Panel1由Panel2、Panel3组成;b、(1)、在Panel6添加一个按钮并将border设置成LoweredBevel,设置按钮大小,并给按钮命名(2)、将Panel7的layout 设置成FlowLayout,并添加三个按钮,设置按钮大小,并给按钮命名(3)、将Panel5的layout 设置成gridLayout,并添加四个按钮,设置按钮大小,并给按钮命名(4)、将Panel4的layout 设置成gridLayout,并添加二十个按钮,设置按钮大小,并给按钮命名2、给对应按钮添加方法,实现起相应的功能三、实验结果1、计算器界面2、实现功能能进行整数基本的加减乘除运算、及其连续运算、清零。

四、讨论与分析1、此实验主要是进行计算器界面的布局,根据电脑上的计算器设计布局主要设置了七个Panel来将界面分成几个部分。

且Panel都是用borderLayout来进行的布局。

2、刚刚开始不能实现连续运算,本程序的设计思路是,读取两次文本框的内容赋值给a,b。

后来在原来的基础上增加了一个标志位,判断符号是不是第一次输入,如果不是则调用等于按钮功能,实现与等于相同的功能。

JAVA编写的计算器源代码

JAVA编写的计算器源代码

JAVA编写的计算器源代码// Calculator.javaimport javax.swing.*; // 引入swing库import java.awt.*; // 引入awt库import java.awt.event.*; // 引入awt.event库public class Calculator extends JFrame implements ActionListener//定义按钮private JButton zero;private JButton one;private JButton two;private JButton three;private JButton four;private JButton five;private JButton six;private JButton seven;private JButton eight;private JButton nine;private JButton point;private JButton equal; private JButton plus; private JButton minus; private JButton multiply; private JButton divide; private JButton backspace; private JButton ac;private JButton ce;private JButton sqrt; private JButton sqr;private JButton plus_minus; private JButton delete; private JButton sin;private JButton cos;private JButton tan;private JButton log;private JButton nfactorial; private JButton cubic; private JButton coln;private JButton factorial;//定义文本框private JTextField resulttext;// 定义boolean变量boolean clrdisp = true; // 昵称确定是否清除计算器显示boolean isCalculate = false; // 是否可以执行计算// 定义String变量,用于存储操作符String optr;//定义存储第一个操作数double num1;//初始化构造函数public Calculato//设置布局setLayout(new BorderLayout();//创建面板JPanel northPanel = new JPanel(;JPanel centerPanel = new JPanel(;JPanel southPanel = new JPanel(;//设置面板布局northPanel.setLayout(new FlowLayout(); centerPanel.setLayout(new GridLayout(4, 5)); southPanel.setLayout(new FlowLayout();//设置计算器显示resulttext = new JTextField(28); northPanel.add(resulttext);resulttext.setEditable(false);//初始化按钮zero = new JButton("0");one = new JButton("1");two = new JButton("2");three = new JButton("3");four = new JButton("4");five = new JButton("5");six = new JButton("6");seven = new JButton("7");eight = new JButton("8");nine = new JButton("9");point = new JButton(".");equal = new JButton("=");plus = new JButton("+");minus = new JButton("-"); multiply = new JButton("*"); divide = new JButton("/"); backspace = new JButton("<-"); ac = new JButton("AC");ce = new JButton("CE");sqrt = new JButton("sqrt");sqr = new JButton("sqr");plus_minus = new JButton("+/-");。

java计算器代码

java计算器代码

//计算器import java.awt.*;import java.awt.event.*;import javax.swing.*;public class Calculator extends WindowAdapter implements ActionListener{JFrame frame;JTextField show;JButton bc,ce,c,ab,jia,jian,cheng,chu,equ,point,sqrt,zf,bfh,ds;//退格,复位,清空,关于,加,减,乘,除,等,点,2,加减,百分之,倒数JButton b[]=new JButton[10];//保存数字JDialog about;final int length=30;int i=0,j=0,action=0,p=0; //记录数字键连续时间次数double num=0,getValue;//记录计算结果的值,保存值public Calculator(){frame=new JFrame("计算器");frame.addWindowListener(this);frame.setSize(360, 230);frame.setLocation(380,260);frame.setLayout(new FlowLayout(FlowLayout.CENTER));frame.setResizable(false);show=new JTextField(31);show.setText("0");show.setHorizontalAlignment(SwingConstants.RIGHT);show.setEnabled(false);frame.add(show);Panel dispTop=new Panel();frame.add(dispTop);dispTop.setLayout(new GridLayout(1,4,3,3));bc=new JButton("BACK");bc.addActionListener(this);dispTop.add(bc);ce=new JButton("CE");ce.addActionListener(this);dispTop.add(ce);c=new JButton("C");c.addActionListener(this);dispTop.add(c);ab=new JButton("ABOUT");ab.addActionListener(this);dispTop.add(ab);//about弹出框about=new JDialog(frame,"关于计算器",true);about.addWindowListener(this);JLabel label=new JLabel("",JLabel.CENTER); about.add(label);about.setSize(200,100);about.setLocation(500,300);//数据显示区Panel dispMain=new Panel();frame.add(dispMain);dispMain.setLayout(new GridLayout(1,2,10,10));//按钮左面板Panel dispLeft=new Panel();frame.add(dispLeft);dispLeft.setLayout(new GridLayout(4,3,3,3));//四行三列//按钮右面板Panel dispRight=new Panel();frame.add(dispRight);dispRight.setLayout(new GridLayout(4,2,3,3));//四行两列for(int l=9;l>=0;l--){b[l]=new JButton(String.valueOf(l));dispLeft.add(b[l]);b[l].addActionListener(this);}zf=new JButton("+/-");zf.addActionListener(this);dispLeft.add(zf);point=new JButton(".");point.addActionListener(this);dispLeft.add(point);chu=new JButton("/");chu.addActionListener(this);dispRight.add(chu);sqrt=new JButton("sqrt");sqrt.addActionListener(this);dispRight.add(sqrt);cheng=new JButton("*");cheng.addActionListener(this);dispRight.add(cheng);bfh=new JButton("%");bfh.addActionListener(this);dispRight.add(bfh);jian=new JButton("-");jian.addActionListener(this);dispRight.add(jian);ds=new JButton("1/x");ds.addActionListener(this);dispRight.add(ds);jia=new JButton("+");jia.addActionListener(this);dispRight.add(jia);equ=new JButton("=");equ.addActionListener(this);dispRight.add(equ);frame.setVisible(true);}//计算器抽象会报错public void actionPerformed(ActionEvent e){getValue=Double.valueOf(show.getText()).doubleValue();for(int k=0;k<10;k++){if(e.getSource()==b[k]){if(i==0){show.setText("");}String str=show.getText();if(str.length()<length){show.setText(show.getText()+e.getActionCommand());}i++;}}if(e.getSource()==jia){if(j==0){num=getValue;}else if(action==1){num+=getValue;}show.setText(String.valueOf(num));j++;action=1;i=0;////}else if(e.getSource()==jian){if(j==0){num=getValue;}else if(action==2){num-=getValue;}show.setText(String.valueOf(num));j++;action=2;i=0;///}else if(e.getSource()==cheng){if(j==0){num=getValue;}else if(action==3){num*=getValue;}show.setText(String.valueOf(num));j++;action=3;i=0;////}else if(e.getSource()==chu){if(j==0){num=getValue;}else if(action==4){num/=getValue;}show.setText(String.valueOf(num));j++;action=4;i=0;////}else if(e.getSource()==equ){switch(action){case 1:show.setText(String.valueOf(num+getValue));break;case 2:show.setText(String.valueOf(num-getValue));break;case 3:show.setText(String.valueOf(num*getValue));break;case 4:show.setText(String.valueOf(num/getValue));break;}//show.setText(String.valueOf(num));j=0;action=0;p=0;i=0;}else if(e.getSource()==point){if(p==0){show.setText(show.getText()+e.getActionCommand());p=1;}}else if(e.getSource()==ce||e.getSource()==c){j=0;action=0;p=0;num=0;i=0;////show.setText("0");}else if(e.getSource()==bc){String str=show.getText();if(str.length()>1){show.setText("");for(int t=0;t<str.length()-1;t++){char c=str.charAt(t);show.setText(show.getText()+c);}}else{show.setText("0");}}else if(e.getSource()==ab){about.setVisible(true);}else if(e.getSource()==sqrt){num=Math.sqrt(getValue);show.setText(String.valueOf(num));j++;i=0;///}else if(e.getSource()==ds){num=1/getValue;show.setText(String.valueOf(num));j++;i=0;////}else if(e.getSource()==bfh){num=getValue/100;show.setText(String.valueOf(num));j++;i=0;}else if(e.getSource()==zf){String str=show.getText();char c=str.charAt(0);if(c=='-'){show.setText("");for(int t=1;t<str.length();t++){show.setText(show.getText()+str.charAt(t));}}else{if(getValue!=0){show.setText("-"+show.getText());}}i=0;}}//windows关闭时调用此方法public void windowClosing(WindowEvent e){ if(e.getSource()==about){about.setVisible(false);}else if(e.getSource()==frame){System.exit(0);}}public static void main(String[] args) {Calculator c1=new Calculator();}}。

eclipse实现简单计算器代码.

eclipse实现简单计算器代码.

eclipse实现简单计算器代码.package Computer;import java.awt.*;import java.awt.event.*;import javax.swing.*;import javax.swing.border.*;import java.util.LinkedList;import java.text.NumberFormat;public class Cacultor extends Frame implements ActionListener{/*** @param args*/NumberButton numberButton[];OperationButton operationButton[];Button 小数点按钮,正负号按钮,退格按钮,求倒数按钮,等号按钮,清零按钮;Panel panel;JTextField resultShow;String 运算符号[]={"+","-","*","/"};LinkedList 链表;boolean 是否按下等号=false;public Cacultor(){super("计算器");链表=new LinkedList();numberButton=new NumberButton[10];for(int i=0;i<=9;i++){numberButton[i]=new NumberButton(i);numberButton[i].addActionListener(this);}operationButton=new OperationButton[4];for(int i=0;i<4;i++){operationButton[i]=new OperationButton(运算符号[i]);operationButton[i].addActionListener(this);}小数点按钮=new Button(".");正负号按钮=new Button("+/-");等号按钮=new Button("=");求倒数按钮=new Button("1/x");退格按钮=new Button("退格");清零按钮=new Button("c");清零按钮.setForeground(Color.red);退格按钮.setForeground(Color.red);等号按钮.setForeground(Color.red);求倒数按钮.setForeground(Color.blue);正负号按钮.setForeground(Color.blue);小数点按钮.setForeground(Color.blue);退格按钮.addActionListener(this);清零按钮.addActionListener(this);等号按钮.addActionListener(this);小数点按钮.addActionListener(this);正负号按钮.addActionListener(this);求倒数按钮.addActionListener(this);resultShow=new JTextField(10);resultShow.setHorizontalAlignment(JTextField.RIGHT); resultShow.setForeground(Color.blue);resultShow.setFont(new Font("TimesRoman",Font.PLAIN,14)); resultShow.setBorder(newSoftBevelBorder(BevelBorder.LOWERED));resultShow.setBackground(Color.white);resultShow.setEditable(false);panel=new Panel();panel.setLayout(new GridLayout(4,5));panel.add(numberButton[1]);panel.add(numberButton[2]);panel.add(numberButton[3]);panel.add(operationButton[0]);panel.add(清零按钮);panel.add(numberButton[4]);panel.add(numberButton[5]);panel.add(numberButton[6]);panel.add(operationButton[1]);panel.add(退格按钮);panel.add(numberButton[7]);panel.add(numberButton[8]);panel.add(numberButton[9]);panel.add(operationButton[2]);panel.add(求倒数按钮);panel.add(numberButton[0]);panel.add(正负号按钮);panel.add(小数点按钮);panel.add(operationButton[3]);panel.add(等号按钮);add(panel,BorderLayout.CENTER);add(resultShow,BorderLayout.NORTH);addWindowListener(new WindowAdapter(){public void windowClosing(WindowEvent e){ System.exit(0);}});setVisible(true);setBounds(100,50,240,180);setResizable(false);validate();}//按钮事件的处理public void actionPerformed(ActionEvent e){if(e.getSource() instanceof NumberButton){NumberButton b=(NumberButton)e.getSource();if(链表.size()==0){int number=b.getNumber();链表.add(""+number);resultShow.setText(""+number);是否按下等号=false;}else if(链表.size()==1&&是否按下等号==false){ int number=b.getNumber();String num=(String)链表.getFirst();String s=num.concat(""+number);链表.set(0, s);resultShow.setText(s);}else if(链表.size()==1&&是否按下等号==true){int number=b.getNumber();链表.removeFirst();链表.add(""+number);是否按下等号=false;resultShow.setText(""+number);}else if(链表.size()==2){int number=b.getNumber();链表.add(""+number);resultShow.setText(""+number);}else if(链表.size()==3){int number=b.getNumber();String num=(String)链表.getLast();String s=num.concat(""+number);链表.set(2, s);resultShow.setText(s);}}else if(e.getSource()instanceof OperationButton){ OperationButton b=(OperationButton)e.getSource();if(链表.size()==1){String fuhao=b.get运算符号();链表.add(fuhao);}else if(链表.size()==2){String fuhao=b.get运算符号();链表.set(1, fuhao);}else if(链表.size()==3){String fuhao=b.get运算符号();String number1=(String)链表.getFirst();String number2=(String)链表.getLast();String 运算符号=(String)链表.get(1);try{double n2=Double.parseDouble(number2); double n=0;if(运算符号.equals("+")){n=n1+n2;}else if(运算符号.equals("-")){n=n1-n2;}else if(运算符号.equals("*")){n=n1*n2;}else if(运算符号.equals("/")){n=n1/n2;}链表.clear();链表.add(""+n);链表.add(fuhao);resultShow.setText(""+n);}catch(Exception ee){}}}else if(e.getSource()==等号按钮){是否按下等号=true;if(链表.size()==1&&链表.size()==2){ String num=(String)链表.getFirst(); resultShow.setText(""+num);}else if(链表.size()==3){String number1=(String)链表.getFirst(); String number2=(String)链表.getLast(); String 运算符号=(String)链表.get(1);try{double n2=Double.parseDouble(number2); double n=0;if(运算符号.equals("+")){n=n1+n2;}else if(运算符号.equals("-")){n=n1-n2;}else if(运算符号.equals("*")){n=n1*n2;}else if(运算符号.equals("/")){n=n1/n2;}resultShow.setText(""+n);链表.set(0, ""+n);链表.removeLast();链表.removeLast();}catch(Exception ee){}}}else if(e.getSource()==小数点按钮){if(链表.size()==0){是否按下等号=false;}else if(链表.size()==1){String dot=小数点按钮.getLabel();String num=(String)链表.getFirst();String s=null;if(num.indexOf(dot)==-1){s=num.concat(dot);链表.set(0, s);}else{s=num;}链表.set(0, s);resultShow.setText(s);}else if(链表.size()==3){String dot=小数点按钮.getLabel(); String num=(String)链表.getLast(); String s=null;if(num.indexOf(dot)==-1){s=num.concat(dot);链表.set(2, s);}else{s=num;}resultShow.setText(s);}}else if(e.getSource()==退格按钮){if(链表.size()==1){String num=(String)链表.getFirst();if(num.length()>=1){num=num.substring(0,num.length()-1); 链表.set(0, num);resultShow.setText(num);}else{链表.removeLast();resultShow.setText("0");}}else if(链表.size()==3){String num=(String)链表.getLast();if(num.length()>=1){num=num.substring(0,num.length()-1); 链表.set(2, num);resultShow.setText(num);}else{链表.removeLast();resultShow.setText("0");}}}else if(e.getSource()==正负号按钮){if(链表.size()==1){String number1=(String)链表.getFirst(); try{double d=Double.parseDouble(number1); d=-1*d;String str=String.valueOf(d);链表.set(0, str);resultShow.setText(str);}catch(Exception ee){}}else if(链表.size()==3){String number2=(String)链表.getLast();try{double d=Double.parseDouble(number2); d=-1*d;String str=String.valueOf(d);链表.set(2, str);resultShow.setText(str);}catch(Exception ee){}}}else if(e.getSource()==求倒数按钮){if(链表.size()==1||链表.size()==2){String number1=(String)链表.getFirst(); try{double d=Double.parseDouble(number1); d=1.0/d;String str=String.valueOf(d);链表.set(0, str);resultShow.setText(str);}catch(Exception ee){}}else if(链表.size()==3){String number2=(String)链表.getLast();try{double d=Double.parseDouble(number2); d=1.0/d;String str=String.valueOf(d);链表.set(0, str);resultShow.setText(str);}catch(Exception ee){}}}else if(e.getSource()==清零按钮){是否按下等号=false;resultShow.setText("0");链表.clear();}}public static void main(String[] args) {// TODO Auto-generated method stub new Cacultor();}}。

java编写的计算器设计报告

java编写的计算器设计报告

java编写的计算器设计报告实验7:综合实验二一、试验目的进一步掌握图形用户界面GUI,了解Swing组件的使用,以及系统提供的该工具的作用,进一步掌握JAVA事件响应机制的原理,更好的掌握面向对象编程的思路。

二、实验要求创建一个界面来实现一个简单的计算器,要求:1、实现最基本的计算器界面,包括:0~9的10个数字按钮,加、减、乘、除、等于5个运算符按钮,一个结果存放的文本区域。

2、实现最基本的加、减、乘、除运算,并能得到正确结果。

3、实现连续的运算,小数点的使用,并考虑各种可能导致异常的情况,将程序作完善;4、可以通过关闭按钮实现关闭窗口。

三、实验步骤、结果1、程序代码:import java.awt.BorderLayout;import java.awt.GridLayout;import java.awt.event.ActionEvent; importjava.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JPanel;import javax.swing.JTextField;import javax.swing.SwingConstants;public class ZhxCacu extends JFrame implements ActionListener { JPanel jpResult = new JPanel();JPanel jpButton = new JPanel();JTextField jtfResult = new JTextField("0");JButton zero = new JButton("0"); //数字键0JButton one = new JButton("1"); //数字键1JButton two = new JButton("2"); //数字键2JButton three = new JButton("3"); //数字键3JButton four = new JButton("4"); //数字键4JButton five = new JButton("5"); //数字键5JButton six = new JButton("6"); //数字键6JButton seven = new JButton("7"); //数字键7JButton eight = new JButton("8"); //数字键8JButton nine = new JButton("9"); // 数字键9JButton plus = new JButton("+");JButton sub = new JButton("-");JButton mul = new JButton("*");JButton div = new JButton("/");JButton equal = new JButton("=");JButton ce = new JButton("ce"); // 置零键JButton point = new JButton(".");JButton tzero = new JButton("00");//com代表敲击运算符,digit代表敲击数字键boolean com = false;boolean digit = false;float total=0;String sum="";int symbol=0;int b,c=0;public ZhxCacu(){// 添加结果输入框并设置对齐方式jpResult.setLayout(new BorderLayout());jpResult.add(jtfResult);jtfResult.setEditable(false);jtfResult.setHorizontalAlignment(SwingConstants.RIGHT); //将组件添加到窗体上this.add(jpResult,"North");this.add(jpButton,"Center");// 定义按钮区域布局管理器为网格布局jpButton.setLayout(new GridLayout(6, 3, 10, 10));// 添加各个按钮键jpButton.add(seven);jpButton.add(eight);jpButton.add(nine);jpButton.add(four);jpButton.add(five);jpButton.add(six);jpButton.add(one);jpButton.add(two);jpButton.add(three);jpButton.add(zero);jpButton.add(tzero);jpButton.add(plus);jpButton.add(sub);jpButton.add(mul);jpButton.add(div);jpButton.add(point);jpButton.add(equal);jpButton.add(ce);one.addActionListener(this);//对1按钮添加监听事件two.addActionListener(this);//对2按钮添加监听事件three.addActionListener(this);//对3按钮添加监听事件four.addActionListener(this);//对4按钮添加监听事件five.addActionListener(this);//对5按钮添加监听事件six.addActionListener(this);//对6按钮添加监听事件seven.addActionListener(this);//对7按钮添加监听事件eight.addActionListener(this);//对8按钮添加监听事件nine.addActionListener(this);//对9按钮添加监听事件zero.addActionListener(this);//对0按钮添加监听事件ce.addActionListener(this);//对置零按钮添加监听事件plus.addActionListener(this);//对+按钮添加监听事件equal.addActionListener(this);//对=按钮添加监听事件sub.addActionListener(this);//对-按钮添加监听事件mul.addActionListener(this);//对*按钮添加监听事件div.addActionListener(this);//对/按钮添加监听事件tzero.addActionListener(this);//对00按钮添加监听事件point.addActionListener(this);//对.按钮添加监听事件pack();//初始化窗体大小最合适大小this.addWindowListener(new WindowAdapter(){public void windowClosing(WindowEvent e){System.exit(0);}});this.setSize(300,300);this.setVisible(true);}public static void main(String[] args) {// TODO 自动生成方法存根new ZhxCacu();}public void actionPerformed(ActionEvent e) {// TODO 自动生成方法存根//数字if(e.getSource()==one){if(com||digit==false){//第一次敲击数字按钮jtfResult.setText("1");com = false;digit = true;}else{sum = jtfResult.getText()+"1"; jtfResult.setText(sum);}}else if(e.getSource()==two){if(com||digit==false){//第一次敲击数字按钮jtfResult.setText("2");com = false;digit = true;}else{sum = jtfResult.getText()+"2"; jtfResult.setText(sum);}}else if(e.getSource()==two){if(com||digit==false){//第一次敲击数字按钮jtfResult.setText("2");com = false;digit = true;}else{sum = jtfResult.getText()+"2"; jtfResult.setText(sum);}}else if(e.getSource()==two){if(com||digit==false){//第一次敲击数字按钮jtfResult.setText("2");com = false;digit = true;}else{sum = jtfResult.getText()+"2"; jtfResult.setText(sum);}}else if(e.getSource()==two){if(com||digit==false){//第一次敲击数字按钮jtfResult.setText("2");com = false;digit = true;}else{sum = jtfResult.getText()+"2"; jtfResult.setText(sum);}}else if(e.getSource()==three){if(com||digit==false){//第一次敲击数字按钮jtfResult.setText("3");com = false;digit = true;}else{sum = jtfResult.getText()+"3"; jtfResult.setText(sum);}}else if(e.getSource()==four){if(com||digit==false){//第一次敲击数字按钮jtfResult.setText("4");com = false;digit = true;}else{sum = jtfResult.getText()+"4"; jtfResult.setText(sum);}}else if(e.getSource()==five){if(com||digit==false){//第一次敲击数字按钮jtfResult.setText("5");com = false;digit = true;}else{sum = jtfResult.getText()+"5"; jtfResult.setText(sum);}}else if(e.getSource()==six){if(com||digit==false){//第一次敲击数字按钮jtfResult.setText("6");com = false;digit = true;}else{sum = jtfResult.getText()+"6"; jtfResult.setText(sum);}}else if(e.getSource()==seven){if(com||digit==false){//第一次敲击数字按钮jtfResult.setText("7");com = false;digit = true;}else{sum = jtfResult.getText()+"7";jtfResult.setText(sum);}}else if(e.getSource()==eight){if(com||digit==false){//第一次敲击数字按钮jtfResult.setText("8");com = false;digit = true;}else{sum = jtfResult.getText()+"8"; jtfResult.setText(sum);}}else if(e.getSource()==nine){if(com||digit==false){//第一次敲击数字按钮jtfResult.setText("9");com = false;digit = true;}else{sum = jtfResult.getText()+"9"; jtfResult.setText(sum);}}else if(e.getSource()==zero){if(com||digit==false){//第一次敲击数字按jtfResult.setText("0");com = false;digit = true;}else{sum = jtfResult.getText()+"0"; jtfResult.setText(sum);if(Float.parseFloat(sum)!=0){}else{if(b==1){sum = jtfResult.getText()+"0"; jtfResult.setText(sum);}elsejtfResult.setText("0");}}}else if(e.getSource()==tzero){if(com||digit==false){//第一次敲击数字按jtfResult.setText("00");com = false;digit = true;}else{sum = jtfResult.getText()+"00";jtfResult.setText(sum);}}else if(e.getSource()==point){if(com||digit==false){//第一次敲击数字按钮b=1;com = true;digit = false;}else if(c==1); else{b=1;sum = jtfResult.getText()+".";jtfResult.setText(sum);c=1;}}//运算else if(e.getSource()==plus){symbol = 1;c=0;total = Float.parseFloat(jtfResult.getText()); com = true;digit = false;}else if(e.getSource()==sub){symbol = 2;c=0;total = Float.parseFloat(jtfResult.getText()); com = true;digit = false;}else if(e.getSource()==mul){symbol = 3;c=0;total = Float.parseFloat(jtfResult.getText()); com = true;digit = false;}else if(e.getSource()==div){symbol = 4;c=0;total = Float.parseFloat(jtfResult.getText()); com = true;digit = false;}else if(e.getSource()==ce){com = true;digit = false;total=0;sum ="0" ;jtfResult.setText(sum);}//=else if(e.getSource()==equal){com = true;digit = false;switch(symbol){case 1:jtfResult.setText(newFloat(total+Float.parseFloat(jtfResult.getText())).toString());b=0;c=0;b reak;case 2:jtfResult.setText(newFloat(total-Float.parseFloat(jtfResult.getText())).toString());b=0;c=0;break;case 3:jtfResult.setText(newFloat(total*Float.parseFloat(jtfResult.getText())).toString());b=0;c =0;break;case 4:if( Float.parseFloat(jtfResult.getText())==0 ){try{throw new Exception();}catch(Exception a){jtfResult.setText("错误~被除数不能为0,请重新输入:");}}elsejtfResult.setText(newFloat(total/Float.parseFloat(jtfResult.getText())).toString());b=0;c =0;break;}digit=false;total = 0;}}}2、界面:四、实验中的问题以及解决方案:1、问题: 被除数为0解决:抛出异常2、问题: 阻止0、小数点在同一数字中重复出现解决: 设置标志,五、总结:1、进一步了解了项目开发的步骤,思路,以及程序的布局和框架结构,尤其是对JAVA的模块化设计有了更为深入的了解。

JAVA计算器源代码

JAVA计算器源代码

计算器源代码一、计算器源代码文件名:computer1.javaimport java.awt.*;import java.awt.event.*;public class computer1 extends Frame implements ActionListener{//声明窗口类并实现动作事件接口。

Button n0,n1,n2,n3,n4,n5,n6,n7,n8,n9;//声明数字按钮Button op,os,om,od,oe,oc;//声明操作按钮TextField tfd;//声明文本框String flg,rslt;//声明标志串、结果串Panel p1,p2,p3;//声明面板int i1,i2;float flt;computer1(){super("加减乘除计算器");n0 = new Button("0");//实现各按钮n1 = new Button("1");n2 = new Button("2");n3 = new Button("3");n4 = new Button("4");n5 = new Button("5");n6 = new Button("6");n7 = new Button("7");n8 = new Button("8");n9 = new Button("9");op = new Button("加");os = new Button("减");om = new Button("乘");od = new Button("除");oe = new Button("=");oc = new Button("c");tfd = new TextField(20);//实现文本框p1=new Panel();//实现各面板p2=new Panel();p3=new Panel();setLayout(new FlowLayout());//布局设计,用于安排按钮位置p1.add(n0);//将各数字按钮放入p1中p1.add(n1);p1.add(n2);p1.add(n3);p1.add(n4);p1.add(n5);p1.add(n6);p1.add(n7);p1.add(n8);p1.add(n9);p2.add(op);//将各操作按钮放入p2、p3中p2.add(os);p2.add(om);p2.add(od);p3.add(oe);p3.add(oc);setLayout(new BorderLayout());//布局设计,用于安排面板位置add("North",tfd);add("West",p1);add("Center",p2);add("East",p3);n0.addActionListener(this);//注册监听器到各按钮n1.addActionListener(this);n2.addActionListener(this);n3.addActionListener(this);n4.addActionListener(this);n5.addActionListener(this);n6.addActionListener(this);n7.addActionListener(this);n8.addActionListener(this);n9.addActionListener(this);op.addActionListener(this);os.addActionListener(this);om.addActionListener(this);od.addActionListener(this);oe.addActionListener(this);oc.addActionListener(this);addWindowListener(new closeWin());setSize(600,100);//确定窗口的尺寸setVisible(true);}public static void main (String args[]){new computer1();}public void actionPerformed(ActionEvent e){//处理鼠标事件的方法try{//异常处理if(e.getSource()==n0)//按数字键时tfd.setText(tfd.getText()+"0");if(e.getSource()==n1)tfd.setText(tfd.getText()+"1");if(e.getSource()==n2)tfd.setText(tfd.getText()+"2");if(e.getSource()==n3)tfd.setText(tfd.getText()+"3");if(e.getSource()==n4)tfd.setText(tfd.getText()+"4");if(e.getSource()==n5)tfd.setText(tfd.getText()+"5");if(e.getSource()==n6)tfd.setText(tfd.getText()+"6");if(e.getSource()==n7)tfd.setText(tfd.getText()+"7");if(e.getSource()==n8)tfd.setText(tfd.getText()+"8");if(e.getSource()==n9)tfd.setText(tfd.getText()+"9");if(e.getSource()==op){//按加号键时i1 = Integer.parseInt(tfd.getText());tfd.setText("");flg = "op";}if(e.getSource()==os){//按减号键时i1 = Integer.parseInt(tfd.getText());tfd.setText("");flg = "os";}if(e.getSource()==om){//按乘号键时i1 = Integer.parseInt(tfd.getText());tfd.setText("");flg = "om";}if(e.getSource()==od){//按除号键时i1 = Integer.parseInt(tfd.getText());tfd.setText("");flg = "od";}if(e.getSource()==oe){//按等号键时i2 = Integer.parseInt(tfd.getText());if(flg=="op"){rslt=Integer.toString(i1+i2);}if(flg=="os"){rslt=Integer.toString(i1-i2);}if(flg=="om"){rslt=Integer.toString(i1*i2);}if(flg=="od"){//除法需做小数处理flt=((float)i1)/((float)i2);rslt=Float.toString(flt);}tfd.setText(rslt);}if(e.getSource()==oc){//按清除键时tfd.setText("");flg = "";}}catch(Exception ex){}//扑捉到异常,但不进行处理}}class closeWin extends WindowAdapter{ //关闭窗口public void windowClosing(WindowEvent e){Frame frm=(Frame)(e.getSource());frm.dispose();System.exit(0);}}二、计算器界面三、修改后计算器界面。

java简易计算器程序输入一行,输出一行

java简易计算器程序输入一行,输出一行

java简易计算器程序输入一行,输出一行Java简易计算器程序是一种功能强大的工具,它可以解决我们日常生活中的许多计算问题。

无论是简单的加法、减法,还是复杂的乘法、除法,这个程序都能迅速、准确地给出答案。

首先,让我们来了解一下它的输入方式。

用户只需在一行中输入算式,使用加号“+”表示加法,减号“-”表示减法,星号“*”表示乘法,斜线“/”表示除法。

例如,输入“5+2”,即代表了一个简单的加法运算。

接下来,让我们看一下程序的输出结果。

它会在一行中返回运算结果,例如输入“5+2”,输出结果将会是“7”。

这种即时反馈,使得计算器程序成为了我们日常生活中的得力助手。

这个简易计算器程序在实际应用中具有广泛的用途。

例如,在购物时,我们可以使用它来计算折扣后的价格。

此外,它还适用于学习、工作中的各种数学问题。

不论是计算面积、求解方程还是处理复杂表达式,这个程序都能为我们提供方便快捷的计算服务。

然而,作为程序的用户,我们也要注意一些使用要点。

首先,输入的算式要满足基本的数学规则,比如除数不能为零,否则程序将无法给出结果。

此外,在进行复杂运算时,可以使用括号来明确计算的先后顺序,提高运算的准确性。

在编写这个简易计算器程序时,我们需要注意程序的设计逻辑和代码的可读性。

良好的设计和清晰的代码结构可以提高程序的可维护性和拓展性。

同时,我们还要考虑异常处理,避免程序在输入错误时崩溃。

总结而言,Java简易计算器程序是一项非常有用且实用的工具。

它的简单易用性和功能全面性使得我们在日常生活和工作中可以更加高效地进行各种数学计算。

因此,掌握并善用这个程序,将为我们的生活带来方便,并为我们的学习与工作提供有力的支持。

java实现简单的加减乘除计算器

java实现简单的加减乘除计算器

java实现简单的加减乘除计算器本⽂实例为⼤家分享了java实现加减乘除计算器的具体代码,供⼤家参考,具体内容如下代码123456 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53import java.awt.*;import java.awt.event.*;import javax.swing.*;import java.awt.FlowLayout;import javax.swing.*;@SuppressWarnings("unused")class Sumjp {JOptionPane jp = new JOptionPane();Sumjp(String str) {JOptionPane.showMessageDialog(null, str);System.exit(0);}Sumjp(String[] str){}}public class JiSuan extends JFrame implements ActionListener,ItemListener{ /****/private static final long serialVersionUID = 1L;double x1,x2,sum = 0;String f;JTextField txt = new JTextField(30);JTextField txt1 = new JTextField(5);JTextField txt2 = new JTextField(5);JTextField txt3 = new JTextField(5);JLabel lb1 = new JLabel("数据1:");JLabel lb2 = new JLabel("符号:");JLabel lb3 = new JLabel("数据2:");JButton jbtn = new JButton("确定");JiSuan(){setSize(350,150);setVisible(true);setTitle("计算器:");setDefaultCloseOperation(EXIT_ON_CLOSE);setLayout(new FlowLayout());add(lb1);add(txt1);// add(lb2);// add(txt2);JComboBox<String> jc = new JComboBox<String>();jc.addItem("加");jc.addItem("减");jc.addItem("乘");jc.addItem("除");545556575859606162636465666768697071727374757677787980818283848586878889add(jc); add(lb3);add(txt3); add(jbtn); add(txt);validate();jc.addItemListener(this);jbtn.addActionListener(this); } public void itemStateChanged(ItemEvent ie){ f = (String)ie.getItem().toString(); }public void actionPerformed(ActionEvent e){x1 = Double.parseDouble(txt1.getText());//f = txt2.getText(); x2 = Double.parseDouble(txt3.getText()); if(f.equals("加")){ sum = x1 + x2;}if(f.equals("减")){sum = x1 - x2; } if(f.equals("乘")){sum = x1*x2;}if(f.equals("")){ sum = x1/x2; }txt.setText(x1 + f + x2 + "=" + sum);new Sumjp(x1 + f + x2 + "=" + sum);}public static void main(String[] args) {// TODO ⾃动⽣成的⽅法存根new JiSuan();} }⼩编再为⼤家分享⼀段代码,感谢作者分享:利⽤java 语法做⼀个很简单的加减乘除计算器:12345678910111213/* 实现思路:1.选择所有数据从键盘输⼊2.使⽤switch 语句进⾏判断3.需要从控制台上输⼊三次 *第⼀个数字 *运算符*第⼆个数字最终在控制台上显⽰:欢迎使⽤简单计算器系统: 请输⼊第⼀个数字:10 请输⼊运算符:+1415161718192021222324252627282930313233343536373839404142434445464748495051525354请输⼊第⼆个数字:20运算结果:10+20=30s.nextInt(); */public class Calculator {public static void main(String[] args){java.util.Scanner s = new java.util.Scanner(System.in); System.out.println("欢迎使⽤简单计算器");System.out.print("请输⼊第⼀个数字:"); int num1 = s.nextInt();System.out.print("请输⼊运算符:"); String operator = s.next(); System.out.print("请输⼊第⼆个数字:"); int num2 = s.nextInt();int result = 0;switch (operator){case "+":result = num1 + num2;break;case "-":result = num1 - num2; break; case "*": result = num1 * num2; break;case "/":result = num1 * num2;break;case "%": result = num1 % num2; } System.out.println(num1+operator+num2+"="+result); }}以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。

java简易计算器完整代码

java简易计算器完整代码

java简易计算器完整代码import java.awt.BorderLayout;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JOptionPane;import javax.swing.JPanel;import javax.swing.JTextField;public class Calculate extends JFrame implements ActionListener {/****/private static final long serialVersionUID = 1L;/*** @param args*/float userFloata=0f;float userFloatb=0f;double result;JLabel label1 ;JLabel label2;JLabel label3;JTextField textField1;JTextField textField2;JTextField textField3;JButton addButton;JButton subtractButton;JButton rideButton;JButton divideButton;public Calculate(){setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);setTitle("简易计算器");JPanel viewJPanel_1=new JPanel();JPanel viewJPanel_2=new JPanel();addButton=new JButton("加");addButton.addActionListener(this);viewJPanel_1.add(addButton);subtractButton=new JButton("减");subtractButton.addActionListener(this);viewJPanel_1.add(subtractButton);rideButton=new JButton("乘");rideButton.addActionListener(this);viewJPanel_1.add(rideButton);divideButton=new JButton("除");divideButton.addActionListener(this);viewJPanel_1.add(divideButton);label1=new JLabel("数据1:");viewJPanel_2.add(label1);textField1=new JTextField(5);textField1.addActionListener(this);viewJPanel_2.add(textField1);label2=new JLabel("数据2:");viewJPanel_2.add(label2);textField2=new JTextField(5);textField2.addActionListener(this);viewJPanel_2.add(textField2);label3=new JLabel("结果是:");viewJPanel_2.add(label3 );textField3=new JTextField(5);viewJPanel_2.add(textField3);setSize(420,120);setVisible(true);validate();getContentPane().add(viewJPanel_1,BorderLayout.NORTH);getContentPane().add(viewJPanel_2,BorderLayout.CENTER);}public void CalculateEventHandel(){try{userFloata= Float.parseFloat(textField1.getText().trim());userFloatb= Float.parseFloat(textField2.getText().trim());} catch (NumberFormatException e) {JOptionPane.showMessageDialog(this, "请输入数字型数据!");textField1.setText("");textField1.requestFocus();textField2.setText("");textField3.setText("");return;}}public static void main(String[] args) { // TODO Auto-generated method stubnew Calculate();//a.CalculateEventHandel();}public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stubif(e.getSource()==addButton){this.CalculateEventHandel();result=userFloata+userFloatb;// System.out.println(""+result);textField3.setText(""+result);}else if(e.getSource()==subtractButton){ this.CalculateEventHandel();result=userFloata-userFloatb;textField3.setText(""+result);}else if(e.getSource()==rideButton){this.CalculateEventHandel();result=userFloata*userFloatb;textField3.setText(""+result);}else if(e.getSource()==divideButton){this.CalculateEventHandel();result=userFloata/userFloatb;textField3.setText(""+result);}}}。

java简易计算器设计思路

java简易计算器设计思路

java简易计算器设计思路Java简易计算器设计思路一、引言计算器是我们日常生活中常用的工具之一,可以帮助我们进行各种简单的数学计算。

本文将介绍如何使用Java编程语言设计一个简易的计算器。

二、功能需求我们的计算器需要具备以下基本功能:1. 实现加、减、乘、除四则运算;2. 能够处理小数、整数和负数的运算;3. 具备清除操作,清零当前计算结果;4. 能够处理连续计算,即进行多次连续的运算。

三、设计思路在设计简易计算器时,我们可以考虑以下步骤:1. 用户界面设计首先,我们需要设计一个用户界面,让用户能够输入数字和选择运算符号。

可以使用Java的Swing或JavaFX进行界面设计。

2. 输入数字和运算符在用户界面中,我们可以使用文本框和按钮来实现数字的输入和运算符的选择。

用户在文本框中输入数字,然后点击相应的按钮选择运算符号。

3. 运算处理根据用户的选择,我们可以利用Java中的if或switch语句来进行相应的运算处理。

比如用户选择加法运算,则获取用户输入的两个数字并相加。

同样,对于减法、乘法和除法运算,我们也可以使用相应的语句进行处理。

4. 显示结果最后,我们需要将计算结果显示在用户界面的文本框中。

将处理后的结果显示在界面上,让用户直观地看到计算结果。

5. 清除操作我们还可以添加一个清除按钮,使用户能够清除当前的计算结果,重新进行新的计算。

四、扩展功能除了基本的计算功能外,我们还可以考虑增加以下扩展功能:1. 添加括号功能,使计算器能够处理复杂的表达式;2. 添加开平方、取余、求幂等高级运算;3. 添加历史记录功能,保存用户之前的计算结果;4. 添加单位转换功能,使计算器能够进行长度、重量、温度等单位之间的转换。

五、总结通过以上设计思路,我们可以实现一个简易的计算器,满足用户的基本计算需求。

同时,我们可以根据实际需求添加扩展功能,提升计算器的实用性和灵活性。

希望本文对您设计和实现一个Java简易计算器有所帮助。

java简易计算机代码

java简易计算机代码

java简易计算机代码Java是一种面向对象的编程语言,广泛应用于计算机编程领域。

下面我们来看一段简易的Java代码,实现一个计算器的功能。

我们需要定义一个Calculator类,代码如下:```javapublic class Calculator {// 定义两个整型变量,用于存储输入的数字private int num1;private int num2;// 构造方法,用于初始化Calculator对象public Calculator(int num1, int num2) {this.num1 = num1;this.num2 = num2;}// 加法运算方法public int add() {return num1 + num2;}// 减法运算方法public int subtract() {return num1 - num2;}// 乘法运算方法public int multiply() {return num1 * num2;}// 除法运算方法public double divide() {// 判断除数是否为0,避免除以0的错误if (num2 != 0) {return (double)num1 / num2;} else {System.out.println("除数不能为0!");return 0;}}// 主方法,程序入口public static void main(String[] args) {// 创建一个Calculator对象,传入两个待计算的数值Calculator calculator = new Calculator(10, 5);// 调用加法运算方法,并输出结果int sum = calculator.add();System.out.println("两数之和:" + sum);// 调用减法运算方法,并输出结果int difference = calculator.subtract();System.out.println("两数之差:" + difference);// 调用乘法运算方法,并输出结果int product = calculator.multiply();System.out.println("两数之积:" + product);// 调用除法运算方法,并输出结果double quotient = calculator.divide();if (quotient != 0) {System.out.println("两数之商:" + quotient);}}}```在上面的代码中,我们首先定义了一个Calculator类,包含了两个私有的整型变量num1和num2,用于存储输入的数字。

java 计算器

java 计算器

Java 计算器的制作一.计算器图形界面:计算器界面包括包括一个输出结果的文本框(JTextField)和20个按钮(JButton),界面布局思路如下:1.将文本框text放置在Jpanel p1中,采用FlowLayout布局;2.将20个按钮放置在Jpanel p2中,采用GridLayout布局;3.将p1,p2放置在JPanel p3中,采用BorderLayout布局;二.按钮功能的实现1.分析:当用户按下相应的按钮后,文本框中应有相应的变换,所以需要添加监视器,对不同的按钮做出不同的反应。

2.计算器实现的功能包括加减乘除,开平方,求倒数,也实现了连续运算的的功能。

3.程序中有很代码均为处理异常,读者可通过去掉这些代码理解其用处。

4.具体实现的代码见三。

三.程序代码1.import javax.swing.*;import javax.swing.text.BadLocationException;import java.awt.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;public class Calculator extends JFrame implements ActionListener{JPanel p1 = new JPanel(new FlowLayout());JPanel p2 = new JPanel(new GridLayout(5,4,3,3));JPanel p3 = new JPanel(new BorderLayout());static JTextField text=new JTextField(18);static int key=0;boolean p= true;static int point=0;double a,b,c;String operator[]={"1","2","3","+","4","5","6","-","7","8","9","×",".","0","=","÷","CE","←","√","1/x"};JButton[] button=new JButton[20];public Calculator(){init();setBounds(100,100,240,350);setVisible(true);setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); }void init(){Color color=Color.WHITE;p1.add(text);text.setText("");for(int i=0;i<20;i++){button[i]=new JButton(operator[i]);button[i].setBackground(color);p2.add(button[i]);button[i].addActionListener(this );}p3.add(p1,BorderLayout.NORTH);p3.add(p2,BorderLayout.CENTER);add(p3);}public void actionPerformed(ActionEvent e){ if(e.getSource()==button[0]){if(key==5){text.setText("1");key=0;}elsetext.setText(text.getText()+"1");}if(e.getSource()==button[1]){if(key==5){text.setText("2");key=0;}elsetext.setText(text.getText()+"2");}if(e.getSource()==button[2]){if(key==5){text.setText("3");key=0;}elsetext.setText(text.getText()+"3");}if(e.getSource()==button[3]){point=0;p=false;String s=text.getText();if(s.equals("+ ")||s.equals("- ")||s.equals("× ")||s.equals("÷ ")){}elsea=Double.valueOf(text.getText());text.setText("+ ");key=1;}if(e.getSource()==button[4]){if(key==5){text.setText("4");key=0;}elsetext.setText(text.getText()+"4");}if(e.getSource()==button[5]){if(key==5){text.setText("5");key=0;}elsetext.setText(text.getText()+"5");}if(e.getSource()==button[6]){if(key==5){text.setText("6");key=0;}elsetext.setText(text.getText()+"6");}if(e.getSource()==button[7]){point=0;p=false;String s=text.getText();if(s.equals("+ ")||s.equals("- ")||s.equals("× ")||s.equals("÷ ")){}elsea=Double.valueOf(text.getText());text.setText("- ");key=2;}if(e.getSource()==button[8]){if(key==5){text.setText("7");key=0;}elsetext.setText(text.getText()+"7");}if(e.getSource()==button[9]){if(key==5){text.setText("8");key=0;}elsetext.setText(text.getText()+"8");}if(e.getSource()==button[10]){if(key==5){text.setText("9");key=0;}elsetext.setText(text.getText()+"9");}if(e.getSource()==button[11]){point=0;p=false;String s=text.getText();if(s.equals("+ ")||s.equals("- ")||s.equals("× ")||s.equals("÷ ")){}elsea=Double.valueOf(text.getText());text.setText("× ");key=3;}if(e.getSource()==button[12]){if(key==5&&point==0){text.setText(".");point++;key=0;}elseif(point==0){text.setText(text.getText()+".");point++;}}if(e.getSource()==button[13]){if(key==5&&!text.getText().equals("0")){text.setText("0");key=0;}else if(!text.getText().equals("0")){text.setText(text.getText()+"0");}}if(e.getSource()==button[14]){if(p){String A=text.getText();a=Double.valueOf(A);String n=A.substring(A.length()-2);if(n.equals(".0")){int aa=(int)a;String h=String.valueOf(aa);text.setText(h);}else{text.setText(n);}}else{String s=Calculator.text.getText();try {b=Double.valueOf( Calculator.text.getText(2,s.length()-2));} catch (NumberFormatException e1) {e1.printStackTrace();} catch (BadLocationException e1) {e1.printStackTrace();}switch(key){case 1:c=a+b;break;case 2:c=a-b;break;case 3:c=a*b;break;case 4:c=a/b;break;}String m=String.valueOf(c);String n=m.substring(m.length()-2);if(n.equals(".0")){int cc=(int)c;m=String.valueOf(cc);}text.setText(m);}key=5;}if(e.getSource()==button[15]){point=0;p=false;String s=text.getText();if(s.equals("+ ")||s.equals("- ")||s.equals("× ")||s.equals("÷ ")){}elsea=Double.valueOf(text.getText());text.setText("÷ ");key=4;}if(e.getSource()==button[16]){point=0;text.setText("");}if(e.getSource()==button[17]){String s=text.getText();String m="";try {m=Calculator.text.getText(0,s.length()-1);} catch (NumberFormatException e1) {text.setText(null);} catch (BadLocationException e1) {text.setText(null);}text.setText(m);String str=".";for(int i=0;i<m.length();i++){if(!str.equals(m.substring(i, i))){ point=0;}}}if(e.getSource()==button[18]){point=0;p=false;a=Double.valueOf(text.getText());double x=Math.sqrt(a);String m=String.valueOf(x);String n=m.substring(m.length()-2);if(n.equals(".0")){int xx=(int)x;m=String.valueOf(xx);}text.setText(m);key=5;}if(e.getSource()==button[19]){point=0;p=false;String h;double a=Double.valueOf(text.getText());double y=1/a;h=String.valueOf(y);String n=h.substring(h.length()-2);if(n.equals(".0")){int yy=(int)y;h=String.valueOf(yy);}text.setText(h);key=5;}}}2.public class Exa {public static void main(String args[]){Calculator win=new Calculator();win.setTitle("计算器");}}四.说明程序在eclipse环境中通过,程序代码中有些java自定义的方法,读者可通过查阅java帮助文档了解其用法和在程序中的作用。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

用JAVA编写计算器程序(模拟Windows计算器)import java.awt.*;import java.awt.event.*;public class Calculation extends WindowAdapter implements ActionListener{double dResult=0;double dNowInput=0;double dMemory;int n=0; //记载小数位数int nOperation=1; // 记录运算符类型int nBitsNum=0; //记录总共输入的位数boolean alreadyHaveDot=false; //已经有小数点?boolean keyAvailable=true;boolean alreadyClickedEqueal=false; //是否按下过"="?boolean isTempNowInput=false; //是否在计算出结果后直接按运算符将结果赋给了当前输入值?Frame f;Panel p1,p2,p3,p4,p5,p6;TextField tf1,tf2;Button b1,b2,b3,b4,b5,b6,b7,b8,b9,b0;Button bDiv,bSqrt,bMulti,bMinus,bPercent,bPlus,bReciprocal,bEqual,bDot,bNegative; Button bBackspace,bCE,bC,bMR,bMS,bMC,bM;public void display(){f=new Frame("计算器");f.setSize(280,213);f.setLocation(200,200);f.setBackground(Color.LIGHT_GRAY);f.setResizable(false);f.setLayout(new BorderLayout(3,3));p1=new Panel(new GridLayout(1,3,5,5)); //用于存放backspace,ce,c三键p2=new Panel(new GridLayout(4,5,5,5)); //用于存放数字区及附近共20键, 此处间隙设置可能不合理,以后调整p3=new Panel(new GridLayout(5,1,5,5)); //用于存放MC,MR,MS,M+键及显示M状态文本框,此处间隙设置可能不合理,以后调整p4=new Panel(new FlowLayout()); //用于存放p1,p2p5=new Panel(new FlowLayout());p6=new Panel(new FlowLayout());p4.add(p1);p4.add(p2);tf1=new TextField(35); //存放显示区tf1.setText("0.");tf1.setEditable(false);p5.add(tf1);f.add(p5,BorderLayout.NORTH);f.add(p4,BorderLayout.CENTER);f.add(p3,BorderLayout.WEST);b1=new Button("1");b2=new Button("2");b3=new Button("3");b4=new Button("4");b5=new Button("5");b6=new Button("6");b7=new Button("7");b8=new Button("8");b9=new Button("9");b0=new Button("0");b1.addActionListener(this);b2.addActionListener(this);b3.addActionListener(this);b4.addActionListener(this);b5.addActionListener(this);b6.addActionListener(this);b7.addActionListener(this);b8.addActionListener(this);b9.addActionListener(this);b0.addActionListener(this);bDiv=new Button("/");bSqrt=new Button("sqrt"); bMulti=new Button("*"); bMinus=new Button("-"); bPercent=new Button("%"); bPlus=new Button("+"); bReciprocal=new Button("1/x"); bEqual=new Button("=");bDot=new Button("."); bNegative=new Button("+/-");bDiv.addActionListener(this); bSqrt.addActionListener(this);bMulti.addActionListener(this); bMinus.addActionListener(this); bPercent.addActionListener(this); bPlus.addActionListener(this); bReciprocal.addActionListener(this); bEqual.addActionListener(this); bDot.addActionListener(this); bNegative.addActionListener(this);p2.add(b7);p2.add(b8);p2.add(b9);p2.add(bDiv);p2.add(bSqrt);p2.add(b4);p2.add(b5);p2.add(b6);p2.add(bMulti);p2.add(bPercent);p2.add(b1);p2.add(b2);p2.add(b3);p2.add(bMinus);p2.add(bReciprocal);p2.add(b0);p2.add(bNegative);p2.add(bDot);p2.add(bPlus);p2.add(bEqual);bBackspace=new Button("Backspace"); bCE=new Button("CE");bC=new Button("C");bBackspace.addActionListener(this); bCE.addActionListener(this);bC.addActionListener(this);p1.add(bBackspace);p1.add(bCE);p1.add(bC);tf2=new TextField(2);tf2.setEnabled(false);tf2.setBackground(Color.LIGHT_GRAY); bMC=new Button("MC");bMR=new Button("MR");bMS=new Button("MS");bM=new Button("M+");bMC.addActionListener(this);bMR.addActionListener(this);bMS.addActionListener(this);bM.addActionListener(this);p6.add(tf2);p3.add(p6);p3.add(bMC);p3.add(bMR);p3.add(bMS);p3.add(bM);f.setVisible(true);f.addWindowListener(this);}public void actionPerformed(ActionEvent e){//key 0 to 9if(this.keyAvailable && e.getActionCommand().length()==1 && e.getActionComman d().compareTo("0")>=0 && e.getActionCommand().compareTo("9")<=0){if(this.isTempNowInput){this.dNowInput=0;this.isTempNowInput=false;}this.nBitsNum++;if(this.alreadyHaveDot==false)this.dNowInput=this.dNowInput*10+Double.parseDouble(e.getActionCommand()); else{double temp=Double.parseDouble(e.getActionCommand());for(int i=this.n;i<0;i++){temp*=0.1;}this.dNowInput+=temp;this.n--;}this.tf1.setText(Double.toString(this.dNowInput));}// key dotif(this.keyAvailable && e.getActionCommand()=="."){if(this.alreadyHaveDot==false){this.nBitsNum++;this.alreadyHaveDot=true;this.n=-1;}}//key "+","-","*","/"if(this.keyAvailable && e.getActionCommand()=="+" || e.getActionCommand()=="-" || e.getActionCommand()=="*" || e.getActionCommand()=="/"){if(this.alreadyClickedEqueal){this.dNowInput=this.dResult;this.isTempNowInput=true;}else{switch(this.nOperation){case 1: this.dResult+=this.dNowInput; break;case 2: this.dResult-=this.dNowInput; break;case 3: this.dResult*=this.dNowInput; break;case 4:{if(this.dNowInput==0){tf1.setText("除数不能为零");this.keyAvailable=false;}else this.dResult=this.dResult/this.dNowInput;}}if(this.keyAvailable)tf1.setText(Double.toString(this.dResult)); this.dNowInput=0;}if(e.getActionCommand()=="+"){this.nOperation=1;}if(e.getActionCommand()=="-"){this.nOperation=2;}if(e.getActionCommand()=="*"){this.nOperation=3;}if(e.getActionCommand()=="/"){this.nOperation=4;}this.nBitsNum=0;this.alreadyClickedEqueal=false;}// key "+/-"if(this.keyAvailable && e.getActionCommand()=="+/-") {this.dNowInput=0-this.dNowInput;tf1.setText(Double.toString(this.dNowInput));}// key "C"if(e.getActionCommand()=="C"){this.nBitsNum=0;this.dResult=0;this.dNowInput=0;this.alreadyHaveDot=false;this.n=0;this.nOperation=1;this.keyAvailable=true;this.alreadyClickedEqueal=false;tf1.setText("0.");}// key "CE"if(e.getActionCommand()=="CE"){this.nBitsNum=0;this.dNowInput=0;this.alreadyHaveDot=false;this.n=0;this.nOperation=1;this.keyAvailable=true;tf1.setText("0.");}// key "sqrt"if(this.keyAvailable && e.getActionCommand()=="sqrt") {if(this.alreadyClickedEqueal){if(this.dResult>=0){this.dResult=Math.sqrt(this.dResult);tf1.setText(Double.toString(this.dResult));}else{tf1.setText("函数输入无效");this.keyAvailable=false;}}else{if(this.dNowInput>=0){this.dNowInput=Math.sqrt(this.dNowInput);tf1.setText(Double.toString(this.dNowInput));}else{tf1.setText("函数输入无效");this.keyAvailable=false;}}// key "1/x"if(this.keyAvailable && e.getActionCommand()=="1/x") {if(this.dNowInput==0){tf1.setText("除数不能为零");this.keyAvailable=false;}else{this.dNowInput=1/this.dNowInput;tf1.setText(Double.toString(this.dNowInput));}}// key "="if(this.keyAvailable && e.getActionCommand()=="=") {this.alreadyClickedEqueal=true;switch(this.nOperation){case 1: this.dResult+=this.dNowInput; break;case 2: this.dResult-=this.dNowInput; break;case 3: this.dResult*=this.dNowInput; break;case 4:{if(this.dNowInput==0){tf1.setText("除数不能为零");this.keyAvailable=false;else this.dResult=this.dResult/this.dNowInput;}}if(this.keyAvailable)tf1.setText(Double.toString(this.dResult)); }// key "MS"if(this.keyAvailable && e.getActionCommand()=="MS"){this.dMemory=this.dNowInput;if(this.dMemory!=0)tf2.setText("M");}// key "MC"if(this.keyAvailable && e.getActionCommand()=="MC"){this.dMemory=0;tf2.setText("");}// key "MR"if(this.keyAvailable && e.getActionCommand()=="MR"){this.dNowInput=this.dMemory;tf1.setText(Double.toString(this.dNowInput));}// key "M+"if(this.keyAvailable && e.getActionCommand()=="M+"){this.dMemory+=this.dNowInput;if(this.dMemory!=0)tf2.setText("M");else tf2.setText("");}// key "%"if(this.keyAvailable && e.getActionCommand()=="%"){this.dNowInput=(this.dResult*this.dNowInput)/100;tf1.setText(Double.toString(this.dNowInput));}// key "Backspace"if(this.keyAvailable && e.getActionCommand()=="Backspace") {if(!this.alreadyClickedEqueal){if(this.dNowInput!=0){if(this.alreadyHaveDot){if(this.n==-1){this.alreadyHaveDot=false;this.n=0;}else{String str,str1;str=tf1.getText();str1=str.substring(0,this.nBitsNum-1);this.nBitsNum--;this.n++;this.dNowInput=Double.parseDouble(str1);tf1.setText(Double.toString(this.dNowInput));}}else{int temp;temp=(int)(this.dNowInput/10);this.dNowInput=(double)temp;tf1.setText(Double.toString(this.dNowInput));}}}}}public static void main(String args[]){Calculation cal=new Calculation();cal.display();}public void windowClosing(WindowEvent e){System.exit(0);}}。

相关文档
最新文档