java简单计算器--代码

合集下载

用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 简单实用计算器代码

//JSQ.javaimport java.awt.*;import java.awt.event.*;import javax.swing.*;public class JSQ{public static void main(String args[]){new MyJSQ("My计算器");}}class MyJSQ extends Frame implements ActionListener{JButton bOption,bNumber;TextField Tresult;int flag=0,perflag;//perflag表示单击了那一个运算符,1表示"+",2表示"-",3表示"*",4表示"/"double op1=0.0,op2=0.0;//操作数StringBuffer str=new StringBuffer();//显示屏所显示的字符串MyJSQ(String s){setTitle(s);Panel conPanel=new Panel();conPanel.setLayout(new BorderLayout());//设置显示屏Panel ptop=new Panel();Tresult=new TextField("0",20);Tresult.setEditable(false);//不可编辑性ptop.add(Tresult);conPanel.add(ptop,BorderLayout.NORTH);//总按键面板Panel pButton=new Panel();Cursor cs=Cursor.getPredefinedCursor(Cursor.HAND_CURSOR);setCursor(cs);pButton.setLayout(new BorderLayout());//操作面板1Panel pUp=new Panel();pUp.setLayout(new GridLayout(2,5,1,1));//(行数,列数,水平间距,垂直间距)bOption=new JButton("x^3");bOption.setForeground(Color.gray);bOption.setMargin(new Insets(3,1,3,5));//setMargin()设置按钮边框和标签之间的空白。

JAVA简易计算器程序源代码

JAVA简易计算器程序源代码

JAVA简易计算器程序源代码package myText;import java.awt.*;import javax.swing.*;import java.awt.event.*;import javax.swing.border.*;public class Calculator extends JFrame implements ActionListener{ private JPanel Panel1=new JPanel();private JPanel Panel2=new JPanel();private JTextField tfResult=new JTextField(25);private JLabel label=new JLabel("计算结果:");private String recentOperation=null;private String recentNum=null;private boolean isNew=true;public void addButton(Container c,String s){JButton b=new JButton(s);b.setFont(new java.awt.Font("SansSerif",0,12));b.setForeground(Color.red);b.setBorder(BorderFactory.createRaisedBevelBorder());c.add(b);b.addActionListener(this);}//end public void addButton(Container c,String s)public void actionPerformed(ActionEvent e){String s=e.getActionCommand();if(s.charAt(0)>='0'&&s.charAt(0)<='9'){if(!isNew){tfResult.setText(tfResult.getText()+s);}//end if(!isNew)else{tfResult.setText(s);}//end elseisNew=false;}//end if(s.charAt(0)>='0'&&s.charAt(0)<='9') else if(s.equals(".")){if(tfResult.getText().indexOf(".")!=-1)return;if(!isNew&&tfResult.getText()!=""){tfResult.setText(tfResult.getText()+".");}//end ifelse{tfResult.setText("0.");}//end elseisNew=false;}//end if(s.equals("."))else if(s.equals("=")){equalaction(e);}//end if(s.equals("="))else{if((tfResult.getText()).equals("")){return;}//endif((tfResult.getText()).equals(""))if(recentOperation!=null){equalaction(e);}//end if(recentOperation!=null) recentOperation=s;recentNum=tfResult.getText();isNew=true;}//end else}//end public void actionPerformed(ActionEvent e) void equalaction(ActionEvent e){if(recentOperation==null||recentNum==null||tfResult.getTex t().equals("")){ return;}//end if()double last=0,now=0;try{last=Double.parseDouble(recentNum);now=Double.parseDouble(tfResult.getText());}//end trycatch(NumberFormatException ne){recentOperation=null;recentNum=null;tfResult.setText("数据输入不合法");System.out.println("数据输入不合法");isNew=true;return;}//end catch(NumberFormatException ne)if(recentOperation.equals("+")){last+=now;}//end if(recentOperation.equals("+"))if(recentOperation.equals("-")){last-=now;}//endif(recentOperation.equals("-"))if(recentOperation.equals("*")){last*=now;}//endif(recentOperation.equals("*"))if(recentOperation.equals("/")){last/=now;}//endif(recentOperation.equals("/"))tfResult.setText(""+last);recentNum=tfResult.getText();recentOperation=null;isNew=true;}//end void equalaction(ActionEvent e)public Calculator(){tfResult.setBorder(BorderFactory.createLoweredBevelBorder ());tfResult.setEditable(false);tfResult.setText("0");tfResult.setHorizontalAlignment(SwingConstants.RIGHT);////本java源代码由839682048整理修改//////Panel1.add(label,FlowLayout.LEFT);Panel1.add(tfResult);////本java源代码由839682048整理修改///Panel2.setLayout(new GridLayout(4,4,2,2));String buttons="789/456*123-0.=+";for(int i=0;i<buttons.length();i++){< p="">addButton(Panel2,buttons.substring(i,i+1));}//end for()//本java源代码由839682048整理修改///this.getContentPane().add(Panel1,"North");this.getContentPane().add(Panel2,"Center");this.setResizable(false);this.setTitle("计算器");this.addWindowListener(newjava.awt.event.WindowAdapter(){public void windowClosing(WindowEvent e){System.exit(0);}});}//end public Calculator1()public static void main(String[]args){Calculator mf=new Calculator();mf.setBounds(200,200,400,400);mf.show();}//end main()}//end public class Calculator1extends JFrame implements ActionListener</buttons.length();i++){<>。

java简易计算器代码

java简易计算器代码

import java.awt.*;import java.awt.event.*;import javax.swing.*;public class ComputerJFrame extends JFrame implements ActionListener {Panel panel = new Panel(new GridLayout(5,4,5,5));//面板采用网格布局 JTextField text=new JTextField("0");double result=0;char ch='#';boolean can=false;public class WindowCloser extends WindowAdapter{p ublic void windowClosing(WindowEvent we){System.exit(0);}}public ComputerJFrame(){super("计算器");this.setSize(280,210);this.setLocation(300,240);this.setDefaultCloseOperation(EXIT_ON_CLOSE); //单击窗口关闭按钮时,结束程序运行setLayout(new BorderLayout());//将text和panel进行边布局add("North",text);text.setHorizontalAlignment(JTextField.RIGHT);text.setEditable(false);add("South",panel);Stringstr[]={"sqrt","+/-","Backspace","C","7","8","9","/","4","5","6","*"," 1","2","3","-","0",".","=","+"};JButton buttons[] = new JButton[str.length];for (int i=0; i<buttons.length; i++){buttons[i] = new JButton(str[i]);panel.add(buttons[i]);buttons[i].addActionListener(this); //为按钮注册单击事件监听器}//addWindowListener(new WindowCloser());//关闭窗口pack();setVisible(true);}public void actionPerformed(ActionEvent e){String current=e.getActionCommand();//获得事件源标题boolean first=false;//是否为第一个字符if(current=="C"){ //C键清空文本框text.setText("0");ch='#';return;}if (current=="Backspace") //退格{ //将text中的内容的最后一个数字去掉,赋值给str/*Stringstr=text.getText().substring(0,text.getText().length()-1);text.setText(str);//将text的内容设置为str的值if (str==""){text.setText("0");first = true;}*/if(text.getText().length()-1>0)text.setText(text.getText().substring(0,text.getText().length()-1));else text.setText("0");return;}if(current=="sqrt"){ // 开平方根class MyException extends Exception { //内部类void test(double x) throws MyException{if(x<0.0) throw new MyException();else text.setText(String.valueOf(Math.sqrt(x)));}}MyException n=new MyException();try{double f = Double.parseDouble(text.getText());//取出text中显示的数字n.test(f);}catch(MyException nfe){JOptionPane.showMessageDialog(this,"\""+text.getText()+"\" 负数不能开平方根,请重新输入数字!");}/* double f = Double.parseDouble(text.getText());if(f<0) return;else {f=Math.sqrt(f);String str=String.valueOf(f);//将实型数据f转化为字符串型text.setText(str);}*/}if(current=="+/-"){ //取相反数if(text.getText().charAt(0)!='-')text.setText('-'+text.getText());elsetext.setText(text.getText().substring(1,text.getText().length()));}if(current=="."){ //小数点int i=0;char c=text.getText().charAt(i);while(i<=text.getText().length()-1){if(text.getText().charAt(i)!='.')i++;else break;}if(i==text.getText().length())text.setText(text.getText()+".");elsetext.setText(text.getText());return;}/*if(current=="."){ //小数点t ext.setText(text.getText()+".");r eturn;}*/if(current.charAt(0)>='0'&&current.charAt(0)<='9'){//0~9数字键if(can){text.setText(current);can=false;}else{if(Double.parseDouble(text.getText())==0)text.setText(current);else text.setText(text.getText()+current);}}if(current=="+"||current=="-"||current=="*"||current=="/"){if(ch!='#'){//连续几个数进行运算try{result=computer(result,ch,Double.parseDouble(text.getText()));text.setText(String.valueOf(result));ch=current.charAt(0);can=true;return;}catch(NumberFormatException num){JOptionPane.showMessageDialog(this,"数字格式出错!");}}else{try{result=Double.parseDouble(text.getText());ch=current.charAt(0);can=true;return;}catch(NumberFormatException num){JOptionPane.showMessageDialog(this,"数字格式出错!");}}}if(current=="="){c an=true;t ry{if(ch=='#')return;else{double result0=Double.parseDouble(text.getText());result=computer(result,ch,result0);text.setText(String.valueOf(result));ch='#';return;}}c atch(NumberFormatException num){JOptionPane.showMessageDialog(this,"数字格式出错!");}}}public double computer(double a,char c,double b){//加减乘除计算d ouble s;s witch(c){c ase'+':s=a+b;break;c ase'-':s=a-b;break;c ase'*':s=a*b;break;c ase'/':if(b==0){JOptionPane.showMessageDialog(this," 除0错误!");return 0;}else s=a/b;break;d efault:return 0;}r eturn s;}public static void main(String[] args){ComputerJFrame mf=new ComputerJFrame();}}运行结果:(以1234+140为例来演示运行过程)1..运行打开计算机2.输入数字123453.按Bacespace键将5删除4.按“+”号后输入另一个加数1405.按“=”号,显示结果6.按清空“C”键。

java——简单计算器

java——简单计算器

源文件一:calculation.javaimport java.util.LinkedList;public class calculation {intermediary itmd=intermediary.getIntermediary();LinkedList<String> fomula=itmd.getFomula();OperationFactory opf=new OperationFactory();public void calculat(){double result=0;int flag=0;//标志是否有括号,1表示有括号//n记录最后一个正括号的位置,i记录第一个反括号的位置for(int i=0,n=0;i<fomula.size();i++){System.out.print(fomula.get(i));//输出集合元素if(fomula.get(i).equals("(")){while(fomula.get(i).equals("(")){i++;}n=i;i++;while(!fomula.get(i).equals(")")){i++;}simpCalculat(n,i-1);fomula.remove(n+1);fomula.remove(n-1);result=Double.valueOf(fomula.get(n-1));i=-1;n=0;}}if(fomula.size()<3){if(!(fomula.get(0) instanceof String ))result=Double.valueOf(fomula.get(0));elseresult=Double.valueOf(fomula.get(1));itmd.setResult(result);}else{result=simpCalculat(0,fomula.size()-1);itmd.setResult(result);}}private double simpCalculat(int n,int m){double result =0;// for(int i=0,n=0;i<fomula.size()-1;i++){while(n<m-1){// if(fomula.get(n+1) instanceof String){for(int i=n;i<m;i++){if(fomula.get(i).equals("*")||fomula.get(i).equals("/")){ Operation op=opf.creatOperate((String)fomula.get(i));op.setNumber(Double.valueOf(fomula.get(i-1)) ,Double.valueOf(fomula. get(i+1)));result=op.getResult();fomula.remove(i);fomula.remove(i);fomula.set(i-1, ((Double)result).toString());m=m-2;}}for(int i=n;i<m;i++){Operation op=opf.creatOperate((String)fomula.get(n+1));op.setNumber(Double.valueOf(fomula.get(n)),Double.valueOf(fomula.get (n+2)));result=op.getResult();fomula.remove(n+1);fomula.remove(n+1);fomula.set(n, ((Double)result).toString());m=m-2;}}return result;}}源文件二:intermediary.javaimport java.util.LinkedList;/*** 中介类:* 从前台接受输入的数据,并传入后台计算* 将后台计算好的结果传入前台* @author Administrator**/public class intermediary {private static intermediary itmd=new intermediary();private LinkedList<String> fomula=new LinkedList<String>();//算式集合private double result;//计算结果private intermediary(){}static intermediary getIntermediary(){return itmd;}protected LinkedList<String> getFomula() {int k=0;//运算数与运算符的个数和int begin=0,end=0;for(int i=0;i<fomula.size();i++){int flag=0;//等于一时标志找到第一个数位String s=fomula.get(i);if(s.matches("[0-9.]")&&flag==0){begin=i;flag=1;k++;}if(!s.matches("[0-9.]")&&flag==1){double d1=0,d2=0;int flag2=0;//等于一时表示遇到小数点for(int n=begin;n<end;n++){int a=0;//记录小数点的位置if(s==".")flag2=1;if(flag2!=1){d1=d1+Integer.valueOf(fomula.get(n))*Math.pow(10, i);a=i;}elsed2=d2+Integer.valueOf(fomula.get(n))*Math.pow(0.1,i-a);}Double d=d1+d2;fomula.set(k, d.toString());k=k+2;for(int num=k;num<i;num++){fomula.remove(k);}k++;i=k;}}return fomula;}/*for(int i=0;i<fomula.size();i++){try{String s=fomula.get(i);if(s.matches("[0-9.]"))if(!s.matches("[0-9.]")){double d1=0,d2=0;int flag=0;for(int n=0;n<i;n++){int a=0;if(s==".")flag=1;if(flag!=1){d1=d1+Integer.valueOf(fomula.get(n))*Math.pow(10, i);a=i;}elsed2=d2+Integer.valueOf(fomula.get(n))*Math.pow(0.1,i-a);}Double d=d1+d2;fomula.set(k, d.toString());k=k+2;for(int num=k;num<i;num++){fomula.remove(k);}}else{k++;}i=k;}catch(Exception e){}}*/protected void setFomula(String s) {fomula.add(s);}protected double getResult() {return result;}protected void setResult(double result) {this.result = result;}}源文件三:Operation.javapublic abstract class Operation {protected double numberA;protected double numberB;protected void setNumber(Double numberA,Double numberB) { this.numberA = numberA;this.numberB = numberB;}public abstract double getResult();}源文件四:OperationAdd.javapublic class OperationAdd extends Operation{@Overridepublic double getResult() {// TODO Auto-generated method stubdouble result=0;result=numberA+numberB;return result;}源文件五:OperationDiv.javapublic class OperationDiv extends Operation{@Overridepublic double getResult() {// TODO Auto-generated method stubtry{double result=0;result=numberA/numberB;return result;}catch(ArithmeticException e){System.out.println("算术异常");return 0;}}}源文件六:OperationFactory.javapublic class OperationFactory {public Operation creatOperate(String object){Operation oper=null;switch(object){case"+":oper=new OperationAdd();break;case"-":oper=new OperationSub();break;case"*":oper=new OperationMul();break;case"/":oper=new OperationDiv();break;default:System.out.println("该计算器不具备此种运算的能力");}return oper;}}源文件七:OperationMul.javapublic class OperationMul extends Operation{@Overridepublic double getResult() {// TODO Auto-generated method stubdouble result=0;result=numberA*numberB;return result;}}源文件八:OperationSub.javapublic class OperationSub extends Operation{@Overridepublic double getResult() {// TODO Auto-generated method stubdouble result=0;result=numberA-numberB;return result;}}源文件九:winder.javaimport java.awt.BorderLayout;import java.awt.EventQueue;import javax.swing.JFrame;import javax.swing.JPanel;import javax.swing.border.EmptyBorder;import javax.swing.JButton;import javax.swing.JTextField;import java.awt.event.ActionListener;import java.awt.event.ActionEvent;import java.awt.event.KeyAdapter;import java.awt.event.KeyEvent;import java.awt.event.KeyListener;import java.util.ArrayList;import java.util.LinkedList;public class winder extends JFrame {private JPanel contentPane;private JTextField textField;private String s="";/*** Launch the application.*/public static void main(String[] args) {EventQueue.invokeLater(new Runnable() {public void run() {try {winder frame = new winder();//添加键盘事件frame.addKeyListener(new KeyListener(){public void keyPressed(KeyEvent e){System.out.println(e.getKeyChar());}@Overridepublic void keyReleased(KeyEvent arg0) {// TODO Auto-generated method stub}@Overridepublic void keyTyped(KeyEvent arg0) {// TODO Auto-generated method stub}});frame.setVisible(true);} catch (Exception e) {e.printStackTrace();}}});}/*** Create the frame.*/public winder() {setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);setBounds(100, 100, 276, 338);contentPane = new JPanel();contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));setContentPane(contentPane);contentPane.setLayout(null);JButton btnNewButton = new JButton("1");btnNewButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) {String i=e.getActionCommand();//得到按钮上的字符s=s+i;intermediary.getIntermediary().setFomula(i);textField.setText(s);}});btnNewButton.setBounds(70, 68, 50, 30);contentPane.add(btnNewButton);JButton button = new JButton("/");button.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {String i=e.getActionCommand();//得到按钮上的字符s=s+i;intermediary.getIntermediary().setFomula(i);textField.setText(s);}});button.setBounds(10, 188, 50, 30);contentPane.add(button);JButton button_1 = new JButton("2");button_1.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {String i=e.getActionCommand();//得到按钮上的字符s=s+i;intermediary.getIntermediary().setFomula(i);textField.setText(s);}});button_1.setBounds(130, 68, 50, 30);contentPane.add(button_1);JButton button_2 = new JButton("3");button_2.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {String i=e.getActionCommand();//得到按钮上的字符s=s+i;intermediary.getIntermediary().setFomula(i);textField.setText(s);}});button_2.setBounds(190, 68, 50, 30);contentPane.add(button_2);JButton button_3 = new JButton("+");button_3.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {String i=e.getActionCommand();//得到按钮上的字符s=s+i;intermediary.getIntermediary().setFomula(i);textField.setText(s);}});button_3.setBounds(10, 68, 50, 30);contentPane.add(button_3);JButton button_4 = new JButton("4");button_4.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {String i=e.getActionCommand();//得到按钮上的字符s=s+i;intermediary.getIntermediary().setFomula(i);textField.setText(s);}});button_4.setBounds(70, 108, 50, 30);contentPane.add(button_4);JButton button_5 = new JButton("5");button_5.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {String i=e.getActionCommand();//得到按钮上的字符s=s+i;intermediary.getIntermediary().setFomula(i);textField.setText(s);}});button_5.setBounds(130, 108, 50, 30);contentPane.add(button_5);JButton button_6 = new JButton("6");button_6.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {String i=e.getActionCommand();//得到按钮上的字符s=s+i;intermediary.getIntermediary().setFomula(i);textField.setText(s);}});button_6.setBounds(190, 108, 50, 30);contentPane.add(button_6);JButton button_7 = new JButton("-");button_7.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {String i=e.getActionCommand();//得到按钮上的字符s=s+i;intermediary.getIntermediary().setFomula(i);textField.setText(s);}});button_7.setBounds(10, 108, 50, 30);contentPane.add(button_7);JButton button_8 = new JButton("7");button_8.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {String i=e.getActionCommand();//得到按钮上的字符s=s+i;intermediary.getIntermediary().setFomula(i);textField.setText(s);}});button_8.setBounds(70, 148, 50, 30);contentPane.add(button_8);JButton button_9 = new JButton("8");button_9.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {String i=e.getActionCommand();//得到按钮上的字符s=s+i;intermediary.getIntermediary().setFomula(i);textField.setText(s);}});button_9.setBounds(130, 148, 50, 30);contentPane.add(button_9);JButton button_10 = new JButton("9");button_10.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {String i=e.getActionCommand();//得到按钮上的字符s=s+i;intermediary.getIntermediary().setFomula(i);textField.setText(s);}});button_10.setBounds(190, 148, 50, 30);contentPane.add(button_10);JButton button_11 = new JButton("*");button_11.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {String i=e.getActionCommand();//得到按钮上的字符s=s+i;intermediary.getIntermediary().setFomula(i);textField.setText(s);}});button_11.setBounds(10, 148, 50, 30);contentPane.add(button_11);JButton button_12 = new JButton("0");button_12.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {String i=e.getActionCommand();//得到按钮上的字符s=s+i;intermediary.getIntermediary().setFomula(i);textField.setText(s);}});button_12.setBounds(70, 188, 50, 30);contentPane.add(button_12);JButton button_13 = new JButton(".");button_13.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {String i=e.getActionCommand();//得到按钮上的字符s=s+i;intermediary.getIntermediary().setFomula(i);textField.setText(s);}});button_13.setBounds(130, 188, 50, 30);contentPane.add(button_13);textField = new JTextField();textField.setText("0");textField.setBounds(10, 10, 230, 50);contentPane.add(textField);textField.setColumns(10);JButton button_15 = new JButton("(");button_15.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {String i=e.getActionCommand();//得到按钮上的字符s=s+i;intermediary.getIntermediary().setFomula(i);textField.setText(s);}});button_15.setBounds(10, 228, 50, 30);contentPane.add(button_15);JButton button_16 = new JButton(")");button_16.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {String i=e.getActionCommand();//得到按钮上的字符s=s+i;intermediary.getIntermediary().setFomula(i);textField.setText(s);}});button_16.setBounds(70, 228, 50, 30);contentPane.add(button_16);JButton button_17 = new JButton("=");button_17.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {String i=e.getActionCommand();//得到按钮上的字符intermediary itmd=intermediary.getIntermediary();LinkedList<String> fomula=itmd.getFomula();new calculation().calculat();s=s+i;textField.setText(s+itmd.getResult());fomula.clear();}});button_17.setBounds(190, 188, 60, 70);contentPane.add(button_17);}}。

java简易计算器源代码-5页word资料

java简易计算器源代码-5页word资料

package Swing;import java.awt.BorderLayout;import java.awt.Color;import java.awt.Container;import java.awt.GridLayout;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JOptionPane;import javax.swing.JPanel;import javax.swing.JTextField;public class Work1 {public static void main(String[] args) {new JsqView(340, 240);@SuppressWarnings("serial")class JsqView extends JFrame {JTextField jtf;JButton jb1, jb2, jb3;JButton[] jb;JPanel jp1, jp2, jp3, jp4;MyActionListener l;public JsqView(int weith, int heigh) {Container con = this.getContentPane();con.setLayout(new BorderLayout(5, 10));l = new MyActionListener(this);jtf = new JTextField(26);jp1 = new JPanel();jp1.add(jtf);jtf.setHorizontalAlignment(JTextField.RIGHT);jp3 = new JPanel();jp3.setLayout(new BorderLayout(5, 10));jb1 = new JButton("Backspace");jb2 = new JButton("CE");jb3 = new JButton("C");jb1.setForeground(Color.red);jb1.addActionListener(l);jb2.addActionListener(l);jb2.setForeground(Color.red);jb3.addActionListener(l);jb3.setForeground(Color.red);jp2 = new JPanel();jp2.setLayout(new GridLayout(1, 3, 5, 5));jp2.add(jb1);jp2.add(jb2);jp2.add(jb3);jp4 = new JPanel();jp4.setLayout(new GridLayout(4, 5, 5, 5));jb = new JButton[20];String[] str = { "7", "8", "9", "/", "sqrt", "4", "5", "6", "*", "%","1", "2", "3", "-", "1/x", "0", "+/-", ".", "+", "=" };for (int i = 0; i < 20; i++) {jb[i] = new JButton(str[i]);jb[i].addActionListener(l);if (i == 3 || i == 8 || i == 13 || i == 18 || i == 19) {jb[i].setForeground(Color.red);jp4.add(jb[i]);jp3.add(jp2, BorderLayout.NORTH);jp3.add(jp4);con.add(jp1, BorderLayout.NORTH);con.add(jp3);this.setTitle("计算器");this.setSize(weith, heigh);this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);this.setVisible(true);class MyActionListener implements ActionListener {JsqView jv;char operator;String temp;Count c = new Count();boolean b = false;public MyActionListener(JsqView jv) {this.jv = jv;public void actionPerformed(ActionEvent e) {String str = e.getActionCommand().trim();//System.out.println(str);if (str.matches("[\\d\\.]")) {//System.out.println(str);if(b){jv.jtf.setText("");b = false;StringBuffer sbf = new StringBuffer();String s = jv.jtf.getText().trim();sbf.append(s);if("".equals(s)&&".".equals(str)){sbf.append(0+str);}else if(s.matches("\\d+")){sbf.append(str);}else if(str.matches("\\d")){sbf.append(str);jv.jtf.setText(sbf.toString());} else if (str.matches("[\\+\\-\\*\\/\\%]")) {b =false;operator = str.charAt(0);//System.out.println(str);temp = jv.jtf.getText().trim();jv.jtf.setText("");} else if (str.equals("=")) {String s = jv.jtf.getText().trim();// System.out.println(temp);// System.out.println(s);if("".equals(s)||s==null||temp==null){return;if((temp.matches("\\d+\\.\\d+"))||(s.matches("\\d+\\.\\d+"))){double i = Double.parseDouble(temp);double j = Double.parseDouble(s);if(!b){temp=s;double sum =c.count(i, j, operator,jv);jv.jtf.setText(sum + "");}else{long i = Long.parseLong(temp);long j = Long.parseLong(s);if(!b){temp=s;long sum = c.count(i, j, operator,jv);jv.jtf.setText(sum + "");b = true;}else if(str.equals("1/x")){String s = jv.jtf.getText().trim();double i = Double.parseDouble(s);double sum = c.count(i,jv);jv.jtf.setText(sum + "");b = true;}else if(str.equals("CE")){b= false;jv.jtf.setText("");}else if(str.equals("Backspace")){b= false;jv.jtf.setText(temp);}else if(str.equals("sqrt")){b= true;String s = jv.jtf.getText().trim();double b = Math.sqrt(Double.parseDouble(s));jv.jtf.setText(b+"");}else if(str.equals("+/-")){String s = jv.jtf.getText().trim();if(s.startsWith("-")){s= s.substring(1, s.length());}else{s = "-"+s;jv.jtf.setText(s);class Count {public long count(long i,long j,char operator,JsqView jv){long num = 0;switch (operator) {case '+':num = i + j;break;case '-':num = i - j;break;case '*':num = i * j;break;case '/':if(j==0){try {throw new MyException();} catch (MyException e) {JOptionPane.showMessageDialog(jv, "被除数不能为零","错误",JOptionPane.ERROR_MESSAGE);return 0;num = i / j;break;case '%':num = i % j;break;default:break;return num;public double count(double i,double j,char operator,JsqView jv){double num = 0;switch (operator) {case '+':num = i + j;break;case '-':num = i - j;break;case '*':num = i * j;break;case '/':if(j==0.0){try {throw new MyException();} catch (MyException e) {JOptionPane.showMessageDialog(jv, "被除数不能为零","错误",JOptionPane.ERROR_MESSAGE);return 0;num = i / j;break;default:break;return num;public double count (double i,JsqView jv){double num;if(i==0.0){try {throw new MyException();} catch (MyException e) {JOptionPane.showMessageDialog(jv, "被除数不能为零","错误",JOptionPane.ERROR_MESSAGE);return 0;num = 1/i;return num;@SuppressWarnings("serial")class MyException extends Exception{public MyException(){super("除数不能为零");。

超级简单明了的JAVA计算器代码

超级简单明了的JAVA计算器代码

package caculator;import java.awt.Color;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import javax.swing.*;public class caculator extends JFrame implements ActionListener { double sum=0;static double getValue;static int action ;int i=0,j=0,p=0,l;double par1;JButton Jk=new JButton("k");JButton J1 = new JButton("1");JButton J2 = new JButton("2");JButton J3 = new JButton("3");JButton J4 = new JButton("4");JButton J5 = new JButton("5");JButton J6 = new JButton("6");JButton J7 = new JButton("7");JButton J8 = new JButton("8");JButton J9 = new JButton("9");JButton J0 = new JButton("0");JButton Je = new JButton("=");JButton Ja = new JButton("+");JButton Jr = new JButton("-");JButton Jm = new JButton("*");JButton Jd = new JButton("/");JButton Jc = new JButton("清除");JButton Jpt = new JButton(".");JTextArea show = new JTextArea("");caculator(){super("caculator");setLocation(200,200);setSize(300,350);setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true);JPanel jp = new JPanel();jp.setLayout(null);jp.add(J1);jp.add(J2);jp.add(J3);jp.add(J4);jp.add(J5);jp.add(J6);jp.add(J7);jp.add(J8);jp.add(J9);jp.add(J0);jp.add(Je);jp.add(Ja);jp.add(Jr);jp.add(Jm);jp.add(Jd);jp.add(Jc);jp.add(Je);jp.add(Jpt);J9.setBackground(Color.pink); J8.setBackground(Color.pink); J7.setBackground(Color.pink); J6.setBackground(Color.pink); J5.setBackground(Color.pink); J4.setBackground(Color.pink); J3.setBackground(Color.pink); J2.setBackground(Color.pink); J1.setBackground(Color.pink); J0.setBackground(Color.pink);Je.setBackground(Color.pink);Ja.setBackground(Color.pink); Jr.setBackground(Color.pink); Jm.setBackground(Color.pink); Jd.setBackground(Color.pink); Jc.setBackground(Color.pink); Jpt.setBackground(Color.pink);J7.setBounds(10,70,60,50);J8.setBounds(75,70,60,50);J9.setBounds(140,70,60,50); J4.setBounds(10,125,60,50); J5.setBounds(75,125,60,50); J6.setBounds(140,125,60,50); J1.setBounds(10,180,60,50); J2.setBounds(75,180,60,50); J3.setBounds(140,180,60,50); J0.setBounds(10,235,60,50); Je.setBounds(75,235,60,50); Jpt.setBounds(140,235,60,50);Jd.setBounds(205,70,60,50); Jm.setBounds(205,125,60,50); Jr.setBounds(205,180,60,50); Ja.setBounds(205,235,60,50); Jc.setBounds(205,10,60,50);J1.addActionListener(this);J2.addActionListener(this);J3.addActionListener(this);J4.addActionListener(this);J5.addActionListener(this);J6.addActionListener(this);J7.addActionListener(this);J8.addActionListener(this);J9.addActionListener(this);J0.addActionListener(this);Ja.addActionListener(this);Jr.addActionListener(this);Jm.addActionListener(this);Je.addActionListener(this);Jc.addActionListener(this);Jpt.addActionListener(this);jp.add(show);show.setBackground(Color.pink);show.setBounds(10,10,180,50);setContentPane(jp);}@Overridepublic void actionPerformed(ActionEvent e) { if(e.getSource()==J0){show.setText("0"); }if(e.getSource()==J1){show.setText("1");}if(e.getSource()==J2){show.setText("2");}if(e.getSource()==J3){show.setText("3");}if(e.getSource()==J4){show.setText("4");}if(e.getSource()==J5){show.setText("5");}if(e.getSource()==J6){show.setText("6");}if(e.getSource()==J7){show.setText("7");}if(e.getSource()==J8){show.setText("8");}if(e.getSource()==J9){show.setText("9");}par1=Double.parseDouble(show.getText()); if(e.getSource()==Ja){show.setText("");if(j==0){sum=par1;}else if(action==1){sum+=par1;}setsum();j++;p=0;i=0;action = 1;} if(e.getSource()==Jr){show.setText("");if(j==0){sum=par1;}else if(action==2){sum-=par1;}setsum();j++;p=0;i=0;action = 2;}if(e.getSource()==Jm){show.setText(""); if(j==0){sum=par1;}else if(action==3){sum*=par1;}setsum();j++;p=0;i=0;action = 3;}if(e.getSource()==Jd){show.setText(""); if(j==0){sum=par1;}else if(action==4){sum/=par1;}setsum();j++;p=0;i=0;action = 4;if(e.getSource()==Jc){clear();}if(e.getSource()==Jpt){show.append(".");}if(e.getSource()==Je){switch(action){case 1:show.setText(String.valueOf(sum+=par1)); break;case 2:show.setText(String.valueOf(sum-=par1)); break;case 3:show.setText(String.valueOf(sum*=par1)); break;case 4:show.setText(String.valueOf(sum/=par1)); break;}i=0;j=0;action=0;}}private void setsum() {show.setText(String.valueOf(sum));String s=show.getText();}void clear(){i=0;j=0;p=0;sum=0;action=0;show.setText("0"); }// TODO Auto-generated method stubpublic static void main(String args[]){caculator ct=new caculator();}}。

java简易的计算器代码

java简易的计算器代码

package cn.uoiah.exp4; import java.awt.Color; import java.awt.Container; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JTextField; public class Cal extends JFrame { private Container container; private GridBagLayout layout; //定义布局方式为网格包布局定义布局方式为网格包布局private GridBagConstraints constraints; private JTextField displayField;//计算结果显示区计算结果显示区计算结果显示区private String lastCommand;//保存+,-,*,/,=命令命令private double result;//保存计算结果保存计算结果private boolean start;//判断是否为数开始字的判断是否为数开始字的public Cal() { super("java编写的计算器"); container=getContentPane(); layout=new GridBagLayout(); container.setLayout(layout); constraints=new GridBagConstraints(); // start=true; result=0; lastCommand = "="; //默认执行的操作默认执行的操作displayField=new JTextField(20); //定义计算区域定义计算区域定义计算区域displayField.setHorizontalAlignment(JTextField.RIGHT); //定义计算区域的数字靠右显示显示constraints.gridx=0; constraints.gridy=0; //定义计算区域的定义计算区域的X,Y轴constraints.gridwidth=4; constraints.gridheight=1; //定义计算区域的宽度和高度定义计算区域的宽度和高度定义计算区域的宽度和高度constraints.fill=GridBagConstraints.BOTH; //定义控件填充满剩余空间定义控件填充满剩余空间定义控件填充满剩余空间constraints.weightx=50; constraints.weighty=50; //定义计算区域的轴单位度量值定义计算区域的X,Y轴单位度量值layout.setConstraints(displayField,constraints); container.add(displayField); //将计算区域加入到窗口中将计算区域加入到窗口中ActionListener insert = new InsertAction(); //定义两个监视器定义两个监视器ActionListener command = new CommandAction(); addButton("C",2,1,1,1,insert); addButton("=",3,1,1,1,command); addButton("0",0,2,1,1,insert); addButton("1",1,2,1,1,insert); addButton("2",2,2,1,1,insert); addButton("+",3,2,1,1,command); addButton("3",0,3,1,1,insert); addButton("4",1,3,1,1,insert); addButton("5",2,3,1,1,insert); addButton("-",3,3,1,1,command); addButton("6",0,4,1,1,insert); addButton("7",1,4,1,1,insert); addButton("8",2,4,1,1,insert); addButton("*",3,4,1,1,command); addButton("9",0,5,1,1,insert); addButton("+/-",1,5,1,1,insert);//只显示"-"号,"+"没有实用价值没有实用价值addButton(".",2,5,1,1,insert); addButton("/",3,5,1,1,command); setSize(300,300); //设置窗口的大小设置窗口的大小设置窗口的大小setVisible(true); //设置窗口可见设置窗口可见} private void addButton(String label,int row,int column,int with,int height,ActionListener listener) { //定义添加按钮的方法定义添加按钮的方法JButton button=new JButton(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); constraints.insets=new Insets(1,1,1,1);//设置按钮间的间距设置按钮间的间距设置按钮间的间距button.setForeground(Color.MAGENTA); button.setBorderPainted(true); button.setContentAreaFilled(true); button.setBounds(2,2,2,2); button.contains(5,5); } private class InsertAction implements ActionListener { //定义Insert事件的方法事件的方法public void actionPerformed(ActionEvent event) { String input=event.getActionCommand(); if (start) { displayField.setText(""); //默认计算区域为空默认计算区域为空start=false; if(input.equals("+/-")) displayField.setText(displayField.getText()+"-"); //如果开始输入的是"+/-",以负数显示} if(!input.equals("+/-")) { if(input.equals("C")) { displayField.setText("0"); start=true; //实现清零和复位的功能实现清零和复位的功能实现清零和复位的功能} else if(input.equals(".")){ if(displayField.getText().trim().indexOf(".")!=-1){ } else displayField.setText(displayField.getText()+input);//输入小数点时,判断是否已经输入过小数点过小数点} else displayField.setText(displayField.getText()+input); } } } private class CommandAction implements ActionListener { public void actionPerformed(ActionEvent evt) { String command=evt.getActionCommand(); if(start) { lastCommand=command; }else { calculate(Double.parseDouble(displayField.getText())); lastCommand=command; start=true; //记忆输入的操作符号记忆输入的操作符号记忆输入的操作符号} } } public void calculate(double x) { if (lastCommand.equals("+")) result+= x; else if (lastCommand.equals("-")) result-=x; else if (lastCommand.equals("*")) result*=x; else if (lastCommand.equals("/")) result/=x; else if (lastCommand.equals("=")) result=x; //实现计算的功能实现计算的功能 displayField.setText(""+ result); //显示计算的结果显示计算的结果显示计算的结果} public static void main(String[] args) { new Cal(); } } 。

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

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

java代码写的简易计算器(可以实现基本的加减乘除功能)计算器java写⼀个计算器,要求实现加减乘除功能,并且能够循环接收新的数据,通过⽤户交互实现。

import java.util.Scanner;/*** 计算器* 写4个⽅法:加减乘除* 利⽤循环加switch进⾏⽤户交互* 传递需要操作的两个数* 输出结果*/public class Demo04 {public static double a;public static double b;//运算符public static String operator;//=符public static String equal;//结果public static double sum=0;public static void main(String[] args) {Scanner scanner = new Scanner(System.in);System.out.println("输⼊数字:");a = scanner.nextDouble();System.out.println("输⼊运算符:");operator = scanner.next();System.out.println("输⼊数字:");b = scanner.nextDouble();do {switch (operator){case "+":sum= add(a, b);System.out.println("输⼊=获取结果:");equal = scanner.next();coninue();break;case "-":sum=subtract(a,b);System.out.println("输⼊=获取结果:");equal = scanner.next();coninue();break;case "*":sum=multiply(a,b);System.out.println("输⼊=获取结果:");equal = scanner.next();coninue();break;case "/":if (b==0){System.out.println("被除数不能为0");operator = "q";break;}else {sum=divide(a,b);System.out.println("输⼊=获取结果:");equal = scanner.next();coninue();break;}default:System.out.println("运算符输⼊错误!");}}while (operator.equals("+")||operator.equals("-")||operator.equals("*")||operator.equals("/"));scanner.close();}//加public static double add(double a,double b){return a+b;}//减public static double subtract(double a,double b){return a-b;}//乘public static double multiply(double a,double b){return a*b;}//除public static double divide(double a,double b){return a/b;}//获得结果或再次输⼊public static void coninue(){Scanner scanner = new Scanner(System.in);if (equal.equals("=")){System.out.println(a+operator+b+"="+sum);System.out.println("输⼊运算符+,-,*,/继续或输⼊其他字符结束");operator=scanner.next();if (operator.equals("+")||operator.equals("-")||operator.equals("*")||operator.equals("/")){ System.out.println("输⼊数字:");b = scanner.nextDouble();a=sum;}else {System.out.println("输⼊错误!");}}else {System.out.println("输⼊错误!");}}}。

java简单计算器源代码

java简单计算器源代码

简单计算器代码package calcultorthree;import java.awt.BorderLayout;//导入边界布局管理器类import java.awt.GridLayout;//导入网格布局管理器类import java.awt.TextField;// 导入文本区域类import java.awt.event.ActionEvent;〃导入事件类import java.awt.event.ActionListener;〃导入事件监听者类import javax.swing.JButton;// 导入按钮类import javax.swing.JFrame;// 导入窗体import javax.swing.JPanel;〃导入面板*本例实现了简单计算器代码,具备加减乘除和正弦功能,旨在抱砖引玉。

熟悉java的同学,可以在此基础上实现更复杂的功能。

* @author Fjsh*/ public class CalcultorThree {〃新建对象,在构造函数中进行初始化JFrame frame;//新建窗体对象JButton buttonzero,buttondot,buttonequal;// 新建按钮“ 0”". ”"=”JButt on butt on plus,butt onminu s,butt onm ultiple,butt on devisi on,butto nsi n,butt on tozero;// 新建按钮“ +”-""“ * ”" / 和归零按钮JButton butt onon e,butt on two,button three,butt on four,button five,butt on six,butt on seve n,butt on eight,butt onnine;// 新建数字“0”“1 ”“ 2”“ 3”“ 4”“ 5”“ 6”“ 7”“ 8”“ 9”JPa nel pan elwest,pa nelce nter,pa neleast;/新建三个面板TextField tf;//新建文本区域对象public CalcultorThree(){//初始化对象tf=new TextField(30);//构造空文本字段,字符宽度为30frame =new JFrame("CalculatorThree");// 构造窗体对象,名称为“ CalculatorThreepan elce nter= new JPan el();〃构造面板,放到窗体中央pan elwest=new JPa nel();〃构造面板,放到窗体西边pan eleast =new JPa nel();〃构造面板,放到窗体东边Handle h=new Handle();〃新建Handle类对象,Handle类为事件监听类//创建数字按钮对象,1、2、3、4、5、6、7、& 9butt onon e=new JButto n( "1");butto ntwo=new JButto n( "2");butto nthree=new JButto n( "3");butto nfour= new JButto n( "4");butt on five=new JButto n( "5");butto nsix=new JButto n( "6");butt on seve n=new JButt on ("7");butto neight=new JButt on ("8");butt onnin e=new JButt on ("9");panelcenter.setLayout(new GridLayout(3,3));〃设置面板布局为网格布局, 3 行3 列〃将数字按钮添加到中间面板pan elce nter.add(butt onon e);pan elce nter.add(butt on two);pan elce nter.add(butt on three);pan elce nter.add(butt on four);pan elce nter.add(butt on five);pan elce nter.add(butt on six);pan elce nter.add(butt on seve n);pan elce nter.add(butt on eight);pan elce nter.add(butt onnin e);//为10个按钮注册事件监听器butt onon e.addAct ion Liste ner(h);butt on two.addAct ion Liste ner(h);butt on three.addAct ion Liste ner(h);butt on four.addActi on Liste ner(h);butt on five.addAct ion Liste ner(h);butt on six.addAct ion Liste ner(h);butt on seve n. addActi on Liste ner(h);butt on eight.addAct ion Liste ner(h);butt onnin e.addAct ion Liste ner(h);//构造按钮“ 0”“ .',注册事件监听器,设置1行3列的布局,添加到到西边的面板butto nzero=new JButt on ("0");butto ndot =new JButt on (".");butt on equal=new JButt on ("=");butt on zero.addAct ion Liste ner(h);butt on dot.addActi on Liste ner(h);butt on equal.addActi on Liste ner(h);pan elwest.setLayout (new GridLayout(3,1));pan elwest.add(butt on zero);pan elwest.add(butt on dot);pan elwest.add(butt on equal);//构造操作按钮“ +”-”““ *”“/”“sin其'中“>00为归零按钮butto nplus=n ew JButto n("+");butt onminus=new JButt on ("-");butto nmultiple=new JButt on ("*");butt on devisi on=new JButt on ("/");butt onsin=new JButt on ("s in ”);butto ntozero=n ew JButto n( ">0");paneleast.setLayout(new GridLayout(3,1));// 设置西边的布局为3 行1 列〃将操作按钮“ +”- ” ““ * ”“ / ”“添n加到西边的面板中pan eleast.add(butt on plus);pan eleast.add(butt onminu s);pan eleast.add(butt onm ultiple);pan eleast.add(butt on devisi on);pan eleast.add(butt onsin);pan eleast.add(butt on tozero);//为操作按钮“ +”-” ““ * ”“ / ”“注册监听貓”butt on plus.addAct ion Liste ner(h);butt onminu s.addAct ion Liste ner(h);butt onm ultiple.addAct ion Liste ner(h);butt on devisi on .addAct ion Liste ner(h);butt onsin. addActi on Liste ner(h);butt on tozero.addActi on Liste ner(h);frame.setLayout(new BorderLayout());// 设置窗体为边界布局frame.add(pa neleast,"East");〃将东边面板pan eleast添加到窗体的东边frame.add(tf,BorderLayout.NORTH); //将tf文本区域添加到窗体的北边,即顶部frame.add(panelwest,BorderLayout.WEST);〃将panelwest面板添加到窗体西边frame.add(panelcenter,BorderLayout.CENTER);〃将panelcenter面板添加到窗体中间frame.pack();//设置窗体大小,适合其子组件的首选大小和布局frame.setLocation(500,500);// 设置窗体显示位置为(500,500)方式frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);〃设置布局窗体默认关闭frame.setVisible(true);// 设置窗体可见}public static void main( Stri ng[] args) {new CalcultorThree();//主方法中新建对象}class Han die impleme nts Actio nListe ner{〃实现动作监听器类int biaozhi=0;〃此标志标志加减乘除操作double flag1=0,flag2=0,flag3=0;//flag1、flag2 为两个操作数,flag3 为结果@Overridepublic void action Performed(Act ionEvent e) { // 方法重写try{//此处可能会产生异常,用try、catch捕捉异常,不用处理if(e.getSource()==buttondot){〃小数点tf.setText("O.");}if(e.getSource()==buttontozero){// 归零操作tf.setText(””);}if(e.getSource()==buttonzero){〃按键0 操作tf.setText(tf.getText()+"0");flag仁Double.parseDouble(tf.getText());〃将文本区域转换成Double 类型, 赋给flag1}if(e.getSource()==buttonone){// 按键1 操作tf.setText(tf.getText()+"1");flag 仁Double.parseDouble(tf.getText());}else if(e.getSource()==buttontwo){〃按键2 操作tf.setText(tf.getText()+"2");flag 仁Double.parseDouble(tf.getText());}else if(e.getSource()==buttonthree){〃按键3 操作tf.setText(tf.getText()+"3");flag 仁Double.parseDouble(tf.getText());}else if(e.getSource()==buttonfour){〃按键4 操作tf.setText(tf.getText()+"4");flag 仁Double.parseDouble(tf.getText());}else if(e.getSource()==buttonfive){// 按键5 操作tf.setText(tf.getText()+"5");flag 仁Double.parseDouble(tf.getText());}else if(e.getSource()==buttonsix){// 按键6 操作tf.setText(tf.getText()+"6");flag 仁Double.parseDouble(tf.getText());}else if(e.getSource()==buttonseven){〃按键7 操作tf.setText(tf.getText()+"7");flag仁Double.parseDouble(tf.getText());}else if(e.getSource()==buttoneight){〃按键8 操作tf.setText(tf.getText()+"8");flag 仁Double.parseDouble(tf.getText());}else if(e.getSource()==buttonnine){// 按键9 操作tf.setText(tf.getText()+"9");flag 仁Double.parseDouble(tf.getText());}if(e.getSource()==buttonplus){〃加法操作tf.setText(””);flag2=flag1;biaozhi=0;}if(e.getSource()==buttonminus){// 减法操作tf.setText(””);flag2=flag1;biaozhi=1;}if(e.getSource()==buttonmultiple){〃乘法操作tf.setText(””);flag2=flag1;biaozhi=2;}if(e.getSource()==buttondevision){〃除法操作tf.setText(””);flag2=flag1;biaozhi=3;}if(e.getSource()==buttonsin){// 正弦操作flag3=Math.s in( flag1);tf.setText(flag3+"");}if(e.getSource()==buttonequal){〃等号操作,利用biaozhi判断进行相应加减乘除操作if(biaozhi==0){flag3=flag1+flag2;}if(biaozhi==1){flag3=flag1-flag2;}if(biaozhi==2){flag3=flag1*flag2;}if(biaozhi==3){ flag3=flag1/flag2;}tf.setText(flag3+"");}}catch(Excepti on ex){}}}}。

Java制作简易计算器

Java制作简易计算器

Java制作简易计算器(代码)import java.awt.*;import javax.swing.*;import java.awt.event.*;import javax.swing.*;//GUi之前要吧这两个都引进来public class Computer extends JFrame implements ActionListener{//定义组件JButton a1,a2,a3,a4,a5,a6,a7,a8,a9,a0;JButton b1,b2,b3,b4;JButton c1,c2,c3,c4;JTextField t1,t2;JPanel p1,p2;JLabel bq1,bq2;String fuhao;Double count,count2;boolean chose=false,cliks;public static void main(String[] args){Computer l = new Computer();}public Computer(){Font font = new Font("宋体", Font.BOLD, 36);Font font2 = new Font("宋体", Font.BOLD, 20);//实例化组件a1 = new JButton("1");a1.setFont(font);a1.addActionListener(this);a2 = new JButton("2");a2.setFont(font);a2.addActionListener(this);a3 = new JButton("3");a3.setFont(font);a3.addActionListener(this);a4 = new JButton("4");a4.setFont(font);a4.addActionListener(this);a5 = new JButton("5");a5.setFont(font);a5.addActionListener(this); a6 = new JButton("6");a6.setFont(font);a6.addActionListener(this); a7 = new JButton("7");a7.setFont(font);a7.addActionListener(this); a8 = new JButton("8");a8.setFont(font);a8.addActionListener(this); a9 = new JButton("9");a9.setFont(font);a9.addActionListener(this); a0 = new JButton("0");a0.setFont(font);a0.addActionListener(this);b1 = new JButton("清空");b1.addActionListener(this); b2 = new JButton("返回");b2.addActionListener(this); b3 = new JButton(".");b3.addActionListener(this);b4 = new JButton("=");b4.addActionListener(this);c1 = new JButton("+");c1.addActionListener(this);c2 = new JButton("-");c2.addActionListener(this); c3 = new JButton("x");c3.addActionListener(this); c4 = new JButton("÷");c4.addActionListener(this);t1 = new JTextField(25);t2 = new JTextField(35);t1.setFont(font2);t2.setFont(font2);p1 = new JPanel();p2 = new JPanel();bq1 = new JLabel("结");bq2 = new JLabel("果");p1.setLayout(new GridLayout(2,3));p2.setLayout(new GridLayout(4,4));//添加组件p1.add(t1);p1.add(b1);p1.add(b2);p1.add(t2);p1.add(bq1);p1.add(bq2 );p2.add(a1);p2.add(a2);p2.add(a3);p2.add(c1);p2.add(a4);p2.add(a5);p2.add(a6);p2.add(c2);p2.add(a7);p2.add(a8);p2.add(a9);p2.add(c3);p2.add(b3);p2.add(a0);p2.add(b4);p2.add(c4);this.add(p1,BorderLayout.NORTH);this.add(p2,BorderLayout.CENTER);//设置窗口属性this.setSize(460,380);this.setTitle("简易计算器");this.setLocation(200,200);this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);this.setVisible(true);}//事件响应public void actionPerformed(ActionEvent e){Object temp = e.getSource();if(temp == a1){if(chose==true){t1.setText("");t2.setText("");}t1.setText(t1.getText()+""+"1");chose=false;}if(temp == a2){if(chose==true){t1.setText("");t2.setText("");}t1.setText(t1.getText()+""+"2");chose=false;}if(temp == a3){if(chose==true){t1.setText("");t2.setText("");} t1.setText(t1.getText()+""+"3");chose=false;}if(temp == a4){if(chose==true){t1.setText("");t2.setText("");} t1.setText(t1.getText()+""+"4");chose=false;}if(temp == a5){if(chose==true){t1.setText("");t2.setText("");} t1.setText(t1.getText()+""+"5");chose=false;}if(temp == a6){if(chose==true){t1.setText("");t2.setText("");} t1.setText(t1.getText()+""+"6");chose=false;}if(temp == a7){if(chose==true){t1.setText("");t2.setText("");} t1.setText(t1.getText()+""+"7");chose=false;}if(temp == a8){if(chose==true){t1.setText("");t2.setText("");} t1.setText(t1.getText()+""+"8");chose=false;}if(temp == a9){if(chose==true){t1.setText("");t2.setText("");} t1.setText(t1.getText()+""+"9");chose=false;}if(temp == a0){if(chose==true){t1.setText("");t2.setText("");} t1.setText(t1.getText()+""+"0");chose=false;}if(temp==b3){cliks=true;for(int i=0;i<t1.getText().length();i++){ if('.'==t1.getText().charAt(i)){cliks=false;break;}if(cliks==true){t1.setText(t1.getText()+".");}}}if(temp== c1){count=Double.parseDouble(t1.getText());t1.setText("");fuhao = "+";}if(temp== c2){count=Double.parseDouble(t1.getText());t1.setText("");fuhao = "-";}if(temp== c3){count=Double.parseDouble(t1.getText());t1.setText("");fuhao = "*";}if(temp== c4){count=Double.parseDouble(t1.getText());t1.setText("");fuhao = "÷";}if(temp==b1){t1.setText("");t2.setText("");}if(temp==b2){String s=t1.getText();t1.setText("");for(int i=0;i<s.length()-1;i++){char a = s.charAt(i);t1.setText(t1.getText()+a);}}if(temp== b4){count2=Double.parseDouble(t1.getText());t1.setText("");if(fuhao=="+"){//int sum=count+count2;t1.setText(count+""+fuhao+""+count2+""+"=");t2.setText(count+count2+"");chose=true;}if(fuhao=="-"){//int sum=count+count2;t1.setText(count+""+fuhao+""+count2+""+"=");t2.setText(count-count2+"");chose=true;}if(fuhao=="*"){//int sum=count+count2;t1.setText(count+""+fuhao+""+count2+""+"=");t2.setText(count*count2+"");chose=true;}if(fuhao=="÷"){//int sum=count+count2;if(count2==0){t1.setText(count+""+fuhao+""+count2+"");t2.setText("除数不能为0");return;}t1.setText(count+""+fuhao+""+count2+""+"=");t2.setText(count/count2+"");chose=true;}}}}。

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简单计算器代码:```javaimport java.util.Scanner;public class Calculator {public static void main(String[] args) {Scanner input = new Scanner(System.in);double num1, num2, result = 0;char operator;System.out.print("请输入第一个数:");num1 = input.nextDouble();System.out.print("请输入运算符号(+、-、*、/):"); operator = input.next().charAt(0);System.out.print("请输入第二个数:");num2 = input.nextDouble();switch(operator) {case '+':result = num1 + num2;break;case '-':result = num1 - num2;break;case '*':result = num1 * num2;break;case '/':result = num1 / num2;break;default:System.out.println("运算符输入错误,请重新输入!");return;}System.out.println("运算结果:" + num1 + operator + num2 + "=" + result);}}```列表:1. 首先,在程序中导入`java.util.Scanner`包,以便从控制台读取用户输入内容。

Java代码实现计算器加减乘除简易功能

Java代码实现计算器加减乘除简易功能

Java代码实现计算器加减乘除简易功能package test;import javax.swing.*;import java.awt.*;import java.awt.event.KeyAdapter;import java.awt.event.KeyEvent;import java.util.HashMap;import java.util.Stack;/*** Created by zxx on 2020/10/15.*/public class Calculator extends JFrame{private Stack<Double> operandStack= new Stack<>();private Stack<String> operatorStack = new Stack<>();private Calculator(){setTitle("计算器");setSize(266,340);//setSize(400,540);Container c=getContentPane();c.setLayout(null);JTextArea jt=new JTextArea(100,100);jt.setFont(new Font("Aria",Font.BOLD,32));jt.setLineWrap(true);JScrollPane sp=new JScrollPane(jt);jt.setCaretPosition(jt.getDocument().getLength());sp.setBounds(0,0,250,100);c.add(sp);JPanel p=new JPanel();p.setLayout(new GridLayout(5,4,0,0));p.setBounds(0,100,250,200);String[] num={"(",")","AC","/","7","8","9","*","4","5","6","-","1","2","3","+","0",".","DEL","="};JButton[] jb=new JButton[20];for(int i=0;i<20;i ++ ){jb[i]=new JButton(num[i]);p.add(jb[i]);}c.add(p);for(int i=0;i<18;i ++){if(i!=2){final int j=i;jb[i].addActionListener(e-> jt.append(num[j]));}}jb[2].addActionListener(e->{jt.setText("");operandStack.clear();operatorStack.clear();});jb[18].addActionListener(e->{try{jt.setText(jt.getText().substring(0,jt.getText().length()-1));}catch(Exception ignored) { }//忽略这个异常 IDEA就是好⽤!!!});jb[19].addActionListener(e->{try{double x= calculate(jt.getText()+ "#");jt.setText("");jt.append(String.valueOf(x));}catch(Exception ex){if(ex.getMessage()==null)jt.setText("ERROR!");elsejt.setText(ex.getMessage());}});//禁⽌⽂本域的enter换⾏KeyStroke enter = KeyStroke.getKeyStroke("ENTER");jt.getInputMap().put(enter, "none");this.getRootPane().setDefaultButton(jb[19]);c.addKeyListener(new KeyAdapter() {@Overridepublic void keyTyped(KeyEvent e){}public void keyPressed(KeyEvent e) //键盘按键监听{char label=e.getKeyChar();String k=String.valueOf(label);if(label==KeyEvent.VK_ENTER){calculate();}else if(label==KeyEvent.VK_BACK_SPACE){String s = jt.getText();if(s!=null){calculate(); //调⽤定义的处理←⽅法}else{jt.setText(s);}}else{calculate(k); //按下数字和运算符号的叠加}}public void keyReleased(KeyEvent e){}});setVisible(true);setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);}private void calculate(){String b = operatorStack.pop();double c = operandStack.pop();double d = operandStack.pop();double e;if (b.equals("+")) {e = d + c;operandStack.push(e);}if (b.equals("-")) {e = d - c;operandStack.push(e);}if (b.equals("*")) {e = d * c;operandStack.push(e);}if (b.equals("/")) {if(c==0)throw new ArithmeticException("DivideByZero!");//不可修改为Exception// Exception的异常是必须处理的,是受控异常;⽽ArithmeticException 不是必须处理的 ,受控异常必须强制处理 e = d / c;operandStack.push(e);}}private Double calculate(String text){HashMap<String,Integer> precede=new HashMap<>();precede.put("(",0);precede.put(")",0);precede.put("/",2);precede.put("*",2);precede.put("-",1);precede.put("+",1);precede.put("#",0);operatorStack.push("#");int flag=0;for(int i=0;i<text.length();i++ ){String a=String.valueOf(text.charAt(i));if(!a.matches("[0-9.]")){if(flag!=i)operandStack.push(Double.parseDouble(text.substring(flag,i)));flag=i+ 1;while(!(a.equals("#")&&operatorStack.peek().equals("#"))){if(precede.get(a)>precede.get(operatorStack.peek())||a.equals("(")){ operatorStack.push(a);break;}else {if(a.equals(")")) {while(!operatorStack.peek().equals("("))calculate();operatorStack.pop();break;}calculate();}}}}return(operandStack.pop());}public static void main(String[] args){new Calculator();}}。

简单的计算器java代码

简单的计算器java代码

CalculatorCore() {
setupOperators();
setupProcessors();
}
// 为每种命令添加处理方式
private void setupProcessors() {
setupTextbox();
panel.add(textbox, BorderLayout.CENTER);
this.add(panel, BorderLayout.NORTH);
}
// 调整文本框
MyCalculator frame = new MyCalculator("我的计算器");
frame.setVisible(true); // 在桌面上显示窗体
}
}
/**
* 计算器核心逻辑。这个逻辑只能处理 1~2 个数的运算。
this.add(panel, BorderLayout.CENTER);
}
/**
* 在指定的面板上创建按钮
*
* @param panel 要创建按钮的面板
* @param labels 按钮文字
if (label.equals("")) {
panel.add(new JPanel());
JButton(label);
}
});
processors.put("\\.", new Processor() {
public void calculate(String command) {
dotClicked();
}
});
processors.put("C", new Processor() {

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简单计算器代码public class Calculator {public static void main(String[] args) {Calculator calculator = new Calculator(); //创建对象调⽤函数Scanner scanner = new Scanner(System.in); //创建scanner扫描对象,获取⽤户输⼊数据System.out.println("请输⼊第⼀个数据");double a=scanner.nextDouble();System.out.println("请输⼊运算符:");String operator=scanner.next();System.out.println("请输⼊第⼆个数据");double b= scanner.nextDouble();double result=0;//存储最后的计算结果scanner.close();//关闭scanner资源// 根据输⼊的运算符调⽤不同的⽅法if ("+".equals(operator)){//equals判断字符是否相等result= calculator.add(a,b);}//调⽤减法else if ("-".equals(operator)){result=calculator.sub(a,b);}else if ("*".equals(operator)){result=calculator.multiply(a,b);}else if ("/".equals(operator)){result=calculator.div(a,b);}System.out.println("最终结果为"+result);}public double add(double a,double b){return a+b;}public double sub(double a,double b){return a-b;}public double multiply(double a, double b){return a*b;}public double div(double a, double b){return a/b;}}。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
JOptionPane.ERROR_MESSAGE);return;}
}
}
if(act.equals("sqrt")){try{float num=(float)Math.sqrt(Float.parseFloat(t.getText()));
t.setText(String.valueOf(num));can=true;return;
JOptionPane.ERROR_MESSAGE);return;}
}
}
public float cacu(float a,char c,float b){
float sum;
switch(c){
case '+':sum=a+b;break;
case '-':sum=a-b;break;
t.setText(String.valueOf(num));can=true;return;
}catch(NumberFormatException e1){JOptionPane.showMessageDialog(null, "输入格式错误!", "警告!",
JOptionPane.ERROR_MESSAGE);return;}
p1.add(backButton);
p1.add(clearButton);
backButton.addActionListener(this);
clearButton.addActionListener(this);
p2.add(t);
p2.add(p1);
p2.setBackground(Color.black);
p3.setBackground(Color.black);
this.setLayout(new BorderLayout());
this.add(p2,"North");
this.add(p3,"Center");
String buttonStr = "789/A456*B123-C0.D+=";
case '%':if(b==0){JOptionPane.showMessageDialog(null, "除0错误!", "警告!",
JOptionPane.ERROR_MESSAGE);return 0;}sum=a%b;break;
default:return 0;
}
catch(ArithmeticException e1){JOptionPane.showMessageDialog(null, "除0错误!", "警告!",
JOptionPane.ERROR_MESSAGE);return;}
}
if(act.equals("=")){can=true;
}catch(NumberFormatException e1){JOptionPane.showMessageDialog(null, "输入格式错误!", "警告!",
JOptionPane.ERROR_MESSAGE);return;}
}
if(act.equals("1/x")){try{float num=1/Float.parseFloat(t.getText());
case '*':sum=a*b;break;
case '/':if(b==0){JOptionPane.showMessageDialog(null, "除0错误!", "警告!",
JOptionPane.ERROR_MESSAGE);return 0;}sum=a/b;break;
backButton.setFont(new Font("黑体",Font.BOLD,15));
backButton.setForeground(Color.red);
clearButton.setFont(new Font("黑体",Font.BOLD,15));
clearButton.setForeground(Color.red);
String act=e.getActionCommand();
if(e.getSource()==backButton){
if(t.getText().length()>1)t.setText(t.getText().substring(0, t.getText().length()-1));
b.setLabel("+/-");
b.setForeground(Color.blue);
b.setFont(new Font("黑体",Font.BOLD,15));
c.add(b);
b.addActionListener(this);
}
public void actionPerformed(ActionEvent e){
return sum;
}
}�
Button backButton=new Button("退格");
Button clearButton=new Button("清除");
Panel p1 = new Panel(new FlowLayout());
Panel p2 = new Panel(new GridLayout(2,1));
return;
}
else {t.setText(t.getText()+act);return;}
}catch(NumberFormatException e1){
JOptionPane.showMessageDialog(null, "输入格式错误!", "警告!",
if(can){t.setText(act);can=false;}
else{try{if(Float.parseFloat(t.getText())==0)
{if(t.getText().equals("0."))t.setText(t.getText()+act);
else t.setText(act);
if (s.equals("A"))
b.setLabel("sqrt");
else if (s.equals("B"))
b.setLabel("1/x");
else if (s.equals("C"))
b.setLabel("%");
else if (s.equals("D"))
else t.setText("0");
return;}
if(e.getSource()==clearButton){t.setText("0");ch='#';return;}
if(act.equals("+/-")){
if(t.getText().charAt(0)!='-')t.setText("-"+t.getText());
//中南民大08网工二班mz
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import javax.swing.JOptionPane;
public class Calculator extends Applet implements ActionListener{
Panel p3 = new Panel(new GridLayout(4,5,5,5));
TextField t=new TextField("0");
float num1=0;
char ch='#';boolean can=false;
public void init(){
t.setFont(new Font("宋体",Font.BOLD,25));
JOptionPane.ERROR_MESSAGE);return;}
}
else{try{num1=Float.parseFloat(t.getText());
ch=act.charAt(0);can=true;return;
}catch(NumberFormatException e1){JOptionPane.showMessageDialog(null, "输入格式错误!", "警告!",
t.setText(String.valueOf(num1));ch=act.charAt(0);can=true;return;
}catch(NumberFormatException e1){JOptionPane.showMessageDialog(null, "输入格式错误!", "警告!",
JOptionPane.ERROR_MESSAGE);return;}
}
}
if(act.equals("+")||act.equals("-")||act.equals("*")||act.equals("/")||act.equals("%")){
相关文档
最新文档