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简易计算器代码
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'&¤t.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简单计算器--代码
}
}
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);
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简易计算器源代码-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计算器代码
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)源代码
//定义计算的类import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import javax.swing.JTextField;public class Caculate implements ActionListener { //设置属性private String data;private JTextField text;private String result = "0";private boolean start_new = false;private double last_value = 0;private String ope = "";private double value = 0;public String getResult (){return result;}//定义一个构造方法public Caculate(JTextField text){this.text = text;}@Override//按钮事件处理public void actionPerformed(ActionEvent cal) { // TODO Auto-generated method stubdata = cal.getActionCommand();data = data.trim();if("0123456789".indexOf(data) != -1){numButton(data);}else if (".".indexOf(data) != -1){dotButton(data);}else if ("+-*/".indexOf(data) != -1){operateButton(data);}else if ("=".indexOf(data)!=-1){equalButton();}//System.out.println(data);System.out.println(result);text.setText(result);}//计算程序private void numButton(String da){if(!start_new){result = result + da;}else{result = da;}while (result.startsWith("0")&&!result.startsWith("0.")&&result.length()>0){ result = result.substring(1);}start_new = false;}private void dotButton(String da){if(da.indexOf(".")!= -1){result = result + da;}}private void operateButton(String da){if(result.length()>0){last_value = Double.parseDouble(result);ope = da;start_new = true;}}private void equalButton(){value = Double.parseDouble(result);if(ope.equals("+")){result = String.valueOf(last_value + value);}else if(ope.equals("-")){result = String.valueOf(last_value - value);}else if(ope.equals("*")){result = String.valueOf(last_value * value);}else if(ope.equals("/")){if(value == 0){result = "ERROR";}else{result = String.valueOf(last_value / value);}}// 去掉结尾的“.0000...”if (result.matches(".+\\.0+")) {result = result.substring(0, stIndexOf("."));}// 设置状态start_new = true;ope = "";}}import javax.swing.JTextField;public class Culator {private static final String String = null;JTextField op;private String re;/*** @param args*/public static void main(String[] args) {Culator cul = new Culator();cul.init();// TODO Auto-generated method stub}public void init(){javax.swing.JFrame frame = new javax.swing.JFrame(); frame.setTitle("计算器");java.awt.FlowLayout f1= new java.awt.FlowLayout();frame.setLayout(f1);javax.swing.JMenuBar cai = createMB();frame.setJMenuBar(cai);javax.swing.JButton mc = new javax.swing.JButton("MC");op= new javax.swing.JTextField("0",25);//设置数字从右边开始显示op.setHorizontalAlignment(JTextField.RIGHT);//设置按钮javax.swing.JButton mr = new javax.swing.JButton("MR"); javax.swing.JButton ms = new javax.swing.JButton("MS"); javax.swing.JButton mp = new javax.swing.JButton("M+"); javax.swing.JButton mm = new javax.swing.JButton("M-"); javax.swing.JButton delete = new javax.swing.JButton(" ←"); javax.swing.JButton ce = new javax.swing.JButton("CE "); javax.swing.JButton c = new javax.swing.JButton(" C "); javax.swing.JButton pm = new javax.swing.JButton(" ± "); javax.swing.JButton r = new javax.swing.JButton(" √"); javax.swing.JButton seven = new javax.swing.JButton(" 7 "); javax.swing.JButton eight = new javax.swing.JButton(" 8 "); javax.swing.JButton nine = new javax.swing.JButton(" 9 ");javax.swing.JButton under = new javax.swing.JButton(" / ");javax.swing.JButton percent = new javax.swing.JButton(" % ");javax.swing.JButton four = new javax.swing.JButton(" 4 ");javax.swing.JButton five = new javax.swing.JButton(" 5 ");javax.swing.JButton six = new javax.swing.JButton(" 6 ");javax.swing.JButton and = new javax.swing.JButton(" * ");javax.swing.JButton ds = new javax.swing.JButton("1/x");javax.swing.JButton one = new javax.swing.JButton(" 1 ");javax.swing.JButton two = new javax.swing.JButton(" 2 ");javax.swing.JButton three = new javax.swing.JButton(" 3 ");javax.swing.JButton m = new javax.swing.JButton(" - ");javax.swing.JButton equal = new javax.swing.JButton(" = ");javax.swing.JButton zero = new javax.swing.JButton(" 0 ");javax.swing.JButton dot = new javax.swing.JButton(" . ");javax.swing.JButton plus = new javax.swing.JButton(" + ");//添加按钮frame.add(op);frame.add(mc);frame.add(mr);frame.add(ms);frame.add(mp);frame.add(mm);frame.add(delete);frame.add(ce);frame.add(c);frame.add(pm);frame.add(r);frame.add(seven);frame.add(eight);frame.add(nine);frame.add(under);frame.add(percent);frame.add(four);frame.add(five);frame.add(six);frame.add(and);frame.add(ds);frame.add(one);frame.add(two);frame.add(three);frame.add(m);frame.add(equal);frame.add(zero);frame.add(dot);frame.add(plus);frame.setSize(290,300);//实例化一个Caculate类Caculate cal = new Caculate(op);//增加监听op.addActionListener(cal);mc.addActionListener(cal);mr.addActionListener(cal);ms.addActionListener(cal);mp.addActionListener(cal);mm.addActionListener(cal);delete.addActionListener(cal);ce.addActionListener(cal);c.addActionListener(cal);pm.addActionListener(cal);r.addActionListener(cal);seven.addActionListener(cal);eight.addActionListener(cal);nine.addActionListener(cal);under.addActionListener(cal); percent.addActionListener(cal);four.addActionListener(cal);five.addActionListener(cal);six.addActionListener(cal);and.addActionListener(cal);ds.addActionListener(cal);one.addActionListener(cal);two.addActionListener(cal);three.addActionListener(cal);m.addActionListener(cal);equal.addActionListener(cal);zero.addActionListener(cal);dot.addActionListener(cal);plus.addActionListener(cal);frame.setDefaultCloseOperation(3); frame.setResizable(false);frame.setVisible(true);}//创建一个设置TextField窗口容的函数//public void setOp(String re){// op.setText(re);//}//创建一个常带有菜单的菜单条,就加到JFrame上显示private javax.swing.JMenuBar createMB(){//创建菜单条javax.swing.JMenuBar mb = new javax.swing.JMenuBar();//创建查看菜单javax.swing.JMenu view = new javax.swing.JMenu("查看(V)");//创建菜单项javax.swing.JMenuItem biaozhun = new javax.swing.JMenuItem("标准型"); javax.swing.JMenuItem kexue = new javax.swing.JMenuItem("科学型"); javax.swing.JMenuItem chengxu = new javax.swing.JMenuItem("程序员"); javax.swing.JMenuItem tongji = new javax.swing.JMenuItem("统计信息"); javax.swing.JMenuItem history = new javax.swing.JMenuItem("历史");//将菜单项添加到菜单上view.add(biaozhun);view.add(kexue);view.add(chengxu);view.add(tongji);view.add(history);//创建编辑菜单javax.swing.JMenu operation = new javax.swing.JMenu("编辑(O)");//创建菜单项javax.swing.JMenuItem copy = new javax.swing.JMenuItem("复制"); javax.swing.JMenuItem paste = new javax.swing.JMenuItem("黏贴"); javax.swing.JMenuItem hr = new javax.swing.JMenuItem("历史记录");//将菜单项添加到菜单上operation.add(copy);operation.add(paste);operation.add(hr);//创建帮助菜单javax.swing.JMenu help = new javax.swing.JMenu("帮助(H)");//创建帮助菜单项javax.swing.JMenuItem vh = new javax.swing.JMenuItem("查看帮助"); javax.swing.JMenuItem about = new javax.swing.JMenuItem("关于计算器"); //将菜单项添加到菜单上help.add(vh);help.add(about);//加上一个分隔条help.addSeparator();//将菜单添加到菜单条上mb.add(view);mb.add(operation);mb.add(help);return mb;} }。
简易计算器源代码--java
package calculator;import java.awt.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.math.BigDecimal;import javax.swing.*;public class Operation extends JFrame implements ActionListener{/****/private static final long serialVersionUID = 1L;private final String str[] = {"7","8","9","/","4","5","6","*","1","2", "3","-",".","0","=","+"};private final JButton[] JB = new JButton[str.length];private final JButton reset = new JButton("CE");private final JTextField display = new JTextField("");Operation(){super("计算器");JPanel panel1 = new JPanel(new BorderLayout());JPanel panel2 = new JPanel(new GridLayout(4,4));panel1.add(BorderLayout.CENTER, display);panel1.add(BorderLayout.EAST, reset);int i;for( i = 0;i < str.length;i++){JB[i] = new JButton(str[i]);panel2.add(JB[i]);}getContentPane().setLayout(new BorderLayout());getContentPane().add(BorderLayout.NORTH,panel1);getContentPane().add(BorderLayout.SOUTH, panel2);setSize(800,800);for(i = 0;i < str.length;i++){JB[i].addActionListener(this);}reset.addActionListener(this);display.addActionListener(this);setVisible(true);setDefaultCloseOperation((WindowConstants.DISPOSE_ON_CLOSE));pack();}public void actionPerformed(ActionEvent e) {// TODO 自动生成的方法存根Object target = e.getSource();String label = e.getActionCommand();if(target == reset){handlereset();}else if("0123456789.".indexOf(label)>=0){handleNumber(label);}elsehandleOperator(label);}private void handleNumber(String key) {// TODO 自动生成的方法存根if ((isFirstDigit)&&("0123456789".indexOf(key)>=0))display.setText(key);else if ((key.equals(".")))display.setText(display.getText() + ".");else if (!key.equals("."))display.setText(display.getText() + key);isFirstDigit = false;}boolean isFirstDigit = true;double number1 = 0.0;double number2 = 0.0;String operator = "=";BigDecimal df ;private void handlereset() {// TODO 自动生成的方法存根display.setText("");isFirstDigit = true;operator = "=";}public void handleOperator(String key) {if (operator.equals("+")){number1 = Double.valueOf(display.getText());number2 = add(number1,number2);df = new BigDecimal(number2);display.setText(String.valueOf( df.setScale(5, BigDecimal.ROUND_HALF_UP).doubleValue()));}else if (operator.equals("-")){number1 = Double.valueOf(display.getText());number2 = sub(number2,number1);df = new BigDecimal(number2);display.setText(String.valueOf( df.setScale(5, BigDecimal.ROUND_HALF_UP).doubleValue()));}else if (operator.equals("*")){number1 = Double.valueOf(display.getText());number2 = mul(number1,number2);df = new BigDecimal(number2);display.setText(String.valueOf( df.setScale(5, BigDecimal.ROUND_HALF_UP).doubleValue()));}else if (operator.equals("/")){number1 = Double.valueOf(display.getText());if(number1 == 0)display.setText("error");else{number2 = div(number2,number1);df = new BigDecimal(number2);display.setText(String.valueOf( df.setScale(5, BigDecimal.ROUND_HALF_UP).doubleValue()));}}else if (operator.equals("=")){number2 = Double.valueOf(display.getText());display.setText(String.valueOf(number2));}operator = key;isFirstDigit = true;}private double div(double key1, double key2) {// TODO 自动生成的方法存根double result = 0.0;result = key1 / key2;return result;}private double mul(double key1, double key2) {// TODO 自动生成的方法存根double result = 0.0;result = key1 * key2;return result;}private double sub(double key1, double key2) { // TODO 自动生成的方法存根double result = 0.0;result = key1 - key2;return result;}private double add(double key1, double key2) { // TODO 自动生成的方法存根double result = 0.0;result = number1 + number2;return result;}public static void main(String[] args) {new Operation();}}。
简易计算器JAVA实现代码
sall.append("4");
l1.setText(sall.toString());
if(f==0)
s1.append("4");
else
s2.append("4");
}
else if(e.getSource()==b5)
{
sall.append("3");
l1.setText(sall.toString());
if(f==0)
s1.append("3");
else
s2.append("3");
}
else if(e.getSource()==b4)
{
MyFrame f=new MyFrame();
f.setTitle("简易计算器。。。。。");
f.setSize(500,500);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
b1.setBackground(Color.gray);
b1.setFont(font1);
b2.setBackground(Color.gray);
b2.setFont(font1);
b3.setBackground(Color.gray);
b3.setFont(font1);
bf.setBackground(Color.gray);
bf.setFont(font1);
p1.add(b1);
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写⼀个计算器,要求实现加减乘除功能,并且能够循环接收新的数据,通过⽤户交互实现。
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("输⼊错误!");}}}。
简单的计算器源代码
//计算器,已经编译通过import java.awt.*;import java.awt.event.*;import javax.swing.*;public class testZ extends JFrame implements ActionListener{private JPanel jPanel1,jPanel2;private JTextField resultField;private JButton s1,s2,s3,s4,s5,s6,s7,s8,s9,s0,b1,b2,b3,b4,f1,f2; private boolean end,add,sub,mul,div;private String str;private double num1,num2;public testZ(){super("计算器");setSize(300,240);Container con=getContentPane();con.setLayout(new BorderLayout());jPanel1=new JPanel();jPanel1.setLayout(new GridLayout(1,1));jPanel2=new JPanel();jPanel2.setLayout(new GridLayout(4,4));resultField=new JTextField("0");jPanel1.add(resultField);con.add(jPanel1,BorderLayout.NORTH);s1=new JButton(" 1 "); s1.addActionListener(this);s2=new JButton(" 2 "); s2.addActionListener(this);s3=new JButton(" 3 "); s3.addActionListener(this);s4=new JButton(" 4 "); s4.addActionListener(this);s5=new JButton(" 5 "); s5.addActionListener(this);s6=new JButton(" 6 "); s6.addActionListener(this);s7=new JButton(" 7 "); s7.addActionListener(this);s8=new JButton(" 8 "); s8.addActionListener(this);s9=new JButton(" 9 "); s9.addActionListener(this);s0=new JButton(" 0 "); s0.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);f1=new JButton(" . "); f1.addActionListener(this);f2=new JButton(" = "); f2.addActionListener(this);jPanel2.add(s1);jPanel2.add(s2);jPanel2.add(s3);jPanel2.add(b1);jPanel2.add(s4);jPanel2.add(s5);jPanel2.add(s6);jPanel2.add(b2);jPanel2.add(s7);jPanel2.add(s8);jPanel2.add(s9);jPanel2.add(b3);jPanel2.add(s0);jPanel2.add(f1);jPanel2.add(f2);jPanel2.add(b4);con.add(jPanel2,BorderLayout.CENTER);}public void num(int i){String s = null;s=String.valueOf(i);if(end){//如果数字输入结束,则将文本框置零,重新输入resultField.setText("0");end=false;}if((resultField.getText()).equals("0")){//如果文本框的内容为零,则覆盖文本框的内容resultField.setText(s);}else{//如果文本框的内容不为零,则在内容后面添加数字str = resultField.getText() + s;resultField.setText(str);}}public void actionPerformed(ActionEvent e){ //数字事件 if(e.getSource()==s1)num(1);else if(e.getSource()==s2)num(2);else if(e.getSource()==s3)num(3);else if(e.getSource()==s4)num(4);else if(e.getSource()==s5)num(5);else if(e.getSource()==s6)num(6);else if(e.getSource()==s7)num(7);else if(e.getSource()==s8)num(8);else if(e.getSource()==s9)num(9);else if(e.getSource()==s0)num(0);//符号事件else if(e.getSource()==b1)sign(1);else if(e.getSource()==b2)sign(2);else if(e.getSource()==b3)sign(3);else if(e.getSource()==b4)sign(4);//等号else if(e.getSource()==f1){str=resultField.getText();if(str.indexOf(".")<=1){str+=".";resultField.setText(str);}}else if(e.getSource()==f2){num2=Double.parseDouble(resultField.getText());if(add){num1=num1 + num2;}else if(sub){num1=num1 - num2;}else if(mul){num1=num1 * num2;}else if(div){num1=num1 / num2;}resultField.setText(String.valueOf(num1));end=true;}}public void sign(int s){if(s==1){add=true;sub=false;mul=false;div=false;}else if(s==2){add=false;sub=true;mul=false;div=false;}else if(s==3){add=false;sub=false;mul=true;div=false;}else if(s==4){add=false;sub=false;mul=false;div=true;}num1=Double.parseDouble(resultField.getText()); end=true;}public static void main(String[] args){testZ th1=new testZ();th1.show();}}。
java简单计算器源代码
简单计算器代码package calcultorthree;importjava、awt、BorderLayout;//导入边界布局管理器类import java、awt、GridLayout;//导入网格布局管理器类import java、awt、TextField;//导入文本区域类importjava、awt、event、ActionEvent;//导入事件类importjava、awt、event、ActionListener;//导入事件监听者类importjavax、swing、JButton;//导入按钮类import javax、swing、JFrame;//导入窗体import javax、swing、JPanel;//导入面板/***本例实现了简单计算器代码,具备加减乘除与正弦功能,旨在抱砖引玉。
熟悉java得同学,可以在此基础上实现更复杂得功能。
*author Fjsh*/public class CalcultorThree {//新建对象,在构造函数中进行初始化JFrameframe;//新建窗体对象JButton buttonzero,buttondot,buttonequal;//新建按钮“0"“、”“=”JButton buttonplus,buttonminus,buttonmultiple,buttondevision, buttonsin,buttontozero;//新建按钮“+”“—”“*”“/”“sin"与归零按钮JButton buttonone,buttontwo,buttonthree,buttonfour,buttonfive,buttons ix,buttonseven,buttoneight,buttonnine;//新建数字按钮“0”“1”“2”“3”“4”“5”“6”“7”“8”“9”JPanel panelwest,panelcenter,paneleast;//新建三个面板TextFieldtf;//新建文本区域对象public CalcultorThree(){//初始化对象tf=new TextField(30);//构造空文本字段,字符宽度为30frame=new JFrame(”CalculatorThree");//构造窗体对象,名称为“CalculatorThree"panelcenter=new JPanel();//构造面板,放到窗体中央panelwest=new JPanel();//构造面板,放到窗体西边paneleast=newJPanel();//构造面板,放到窗体东边Handle h=new Handle();//新建Handle类对象,Handle类为事件监听类//创建数字按钮对象,1、2、3、4、5、6、7、8、9buttonone=newJButton(”1”);buttontwo=new JButton(”2");buttonthree=new JButton("3");buttonfour=new JButton("4");buttonfive=newJButton("5”);buttonsix=new JButton(”6”);buttonseven=newJButton("7");buttoneight=new JButton("8");buttonnine=new JButton("9");panelcenter、setLayout(new GridLayout(3,3));//设置面板布局为网格布局,3行3列//将数字按钮添加到中间面板panelcenter、add(buttonone);panelcenter、add(buttontwo);panelcenter、add(buttonthree);panelcenter、add(buttonfour);panelcenter、add(buttonfive);panelcenter、add(buttonsix);panelcenter、add(buttonseven);panelcenter、add(buttoneight);panelcenter、add(buttonnine);//为10个按钮注册事件监听器buttonone、addActionListener(h);buttontwo、addActionListener(h);buttonthree、addActionListener(h);buttonfour、addActionListener(h);buttonfive、addActionListener(h);buttonsix、addActionListener(h);buttonseven、addActionListener(h);buttoneight、addActionListener(h);buttonnine、addActionListener(h);//构造按钮“0"“、"“=”,注册事件监听器,设置1行3列得布局,添加到到西边得面板buttonzero=newJButton("0");buttondot=new JButton(”、”);buttonequal=newJButton("=”);buttonzero、addActionListener(h);buttondot、addActionListener(h);buttonequal、addActionListener(h);panelwest、setLayout(new GridLayout(3,1));panelwest、add(buttonzero);panelwest、add(buttondot);panelwest、add(buttonequal);//构造操作按钮“+”“—"“*”“/”“sin”“>0”,其中“>0”为归零按钮buttonplus=new JButton(”+");buttonminus=new JButton("-”);buttonmultiple=new JButton("*");buttondevision=new JButton(”/");buttonsin=new JButton("sin");buttontozero=newJButton(">0");paneleast、setLayout(new GridLayout(3,1));//设置西边得布局为3行1列//将操作按钮“+”“-"“*"“/"“sin”“>0”添加到西边得面板中paneleast、add(buttonplus);paneleast、add(buttonminus);paneleast、add(buttonmultiple);paneleast、add(buttondevision);paneleast、add(buttonsin);paneleast、add(buttontozero);//为操作按钮“+"“-”“*”“/"“sin”“>0”注册监听器buttonplus、addActionListener(h);buttonminus、addActionListener(h);buttonmultiple、addActionListener(h);buttondevision、addActionListener(h);buttonsin、addActionListener(h);buttontozero、addActionListener(h);frame、setLayout(new BorderLayout());//设置窗体为边界布局frame、add(paneleast,”East”);//将东边面板paneleast添加到窗体得东边frame、add(tf,BorderLayout、NORTH);//将tf文本区域添加到窗体得北边,即顶部frame、add(panelwest,BorderLayout、WEST);//将panelwest 面板添加到窗体西边frame、add(panelcenter,BorderLayout、CENTER);//将panelcent er面板添加到窗体中间frame、pack();//设置窗体大小,适合其子组件得首选大小与布局frame、setLocation(500,500);//设置窗体显示位置为(500,500)frame、setDefaultCloseOperation(JFrame、EXIT_ON_CLOSE);//设置布局窗体默认关闭方式frame、setVisible(true);//设置窗体可见}public static void main(String[]args) {newCalcultorThree();//主方法中新建对象}class HandleimplementsActionListener{//实现动作监听器类intbiaozhi=0;//此标志标志加减乘除操作doubleflag1=0,flag2=0,flag3=0;//flag1、flag2为两个操作数,flag3为结果Overridepublic void actionPerformed(ActionEvent e){//方法重写try{//此处可能会产生异常,用try、catch捕捉异常,不用处理if(e、getSource()==buttondot){//小数点tf、setText(”0、”);}if(e、getSource()==buttontozero){//归零操作tf、setText("");}if(e、getSource()==buttonzero){//按键0操作tf、setText(tf、getText()+”0”);flag1=Double、parseDouble(tf、getText());//将文本区域转换成Double类型,赋给flag1}if(e、getSource()==buttonone){//按键1操作tf、setText(tf、getText()+”1");flag1=Double、parseDouble(tf、getText());}else if(e、getSource()==buttontwo){//按键2操作tf、setText(tf、getText()+”2”);flag1=Double、parseDouble(tf、getText());}else if(e、getSource()==buttonthree){//按键3操作tf、setText(tf、getText()+”3");flag1=Double、parseDouble(tf、getText());}else if(e、getSource()==buttonfour){//按键4操作tf、setText(tf、getText()+"4");flag1=Double、parseDouble(tf、getText());}else if(e、getSource()==buttonfive){//按键5操作tf、setText(tf、getText()+"5”);flag1=Double、parseDouble(tf、getText());}else if(e、getSource()==buttonsix){//按键6操作tf、setText(tf、getText()+”6”);flag1=Double、parseDouble(tf、getText());}else if(e、getSource()==buttonseven){//按键7操作tf、setText(tf、getText()+"7");flag1=Double、parseDouble(tf、getText());}elseif(e、getSource()==buttoneight){//按键8操作tf、setText(tf、getText()+"8");flag1=Double、parseDouble(tf、getText());}else if(e、getSource()==buttonnine){//按键9操作tf、setText(tf、getText()+”9");flag1=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、sin(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(Exception ex){}}}}。
java版计算器源代码
java版计算器源代码:import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import javax.swing.*;import java.awt.*;import java.math.BigDecimal;import java.math.MathContext;import java.math.RoundingMode;import java.awt.Color;/*** java版计算器*/public class Calculator extends JFrame {final int WIN_W = 250, WIN_H = 250;JPanel myPanel, panelSuper;public Calculator() {// 主面板panelSuper = new JPanel();panelSuper.setLayout(null);// 设置窗口位置double width = Toolkit.getDefaultToolkit().getScreenSize().width; double height =Toolkit.getDefaultToolkit().getScreenSize().height;this.setBounds((int) (width - WIN_W) / 2, (int) (height - WIN_H) / 2,WIN_W, WIN_H);// 窗口配置this.setTitle("java版计算器");this.validate();this.setResizable(false);this.setVisible(true);this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);// 添加计算器按钮面板myPanel = new MyPanel();this.add(myPanel, BorderLayout.CENTER);}public static void main(String[] args) {new Calculator();}/*** 计算器按钮面板类*/class MyPanel extends JPanel implements ActionListener {JButton button1, button2, button3, button4, button5, button6, button7,button8, button9, button0, buttonJia, buttonJian, buttonCheng,buttonChu, buttonDeng, buttonDian, buttonC, buttonDel, buttonZF, buttonGH;JTextField jTextField; // 计算器显示屏char oper; // 操作符String key, allKey = "1234567890.±del", jjccKey = " -*/";BigDecimal d1, d2;boolean first;public MyPanel() {// 设置布局this.setLayout(new FlowLayout(FlowLayout.LEFT, 4, 5));// 计算器显示屏jTextField = new JTextField(21);jTextField.setHorizontalAlignment(JTextField.RIGHT);jTextField.setEditable(false);jTextField.setBackground(new Color(255, 255, 255));jTextField.setText("0");this.add(jTextField);// 计算器按钮button1 = new JButton("1");button2 = new JButton("2");button3 = new JButton("3");button4 = new JButton("4");button5 = new JButton("5");button6 = new JButton("6");button7 = new JButton("7");button8 = new JButton("8");button9 = new JButton("9");button0 = new JButton("0");buttonJia = new JButton(" ");buttonJian = new JButton("-");buttonCheng = new JButton("*");buttonChu = new JButton("/");buttonDeng = new JButton("=");buttonDian = new JButton(".");buttonDel = new JButton("del");buttonC = new JButton("c");buttonZF = new JButton("±");buttonGH = new JButton("√");button1.setPreferredSize(new Dimension(55, 30));button2.setPreferredSize(new Dimension(55, 30));button3.setPreferredSize(new Dimension(55, 30));button4.setPreferredSize(new Dimension(55, 30));button5.setPreferredSize(new Dimension(55, 30));button6.setPreferredSize(new Dimension(55, 30));button7.setPreferredSize(new Dimension(55, 30));button8.setPreferredSize(new Dimension(55, 30));button9.setPreferredSize(new Dimension(55, 30));button0.setPreferredSize(new Dimension(55, 30));buttonJia.setPreferredSize(new Dimension(55, 30)); buttonJian.setPreferredSize(new Dimension(55, 30)); buttonCheng.setPreferredSize(new Dimension(55, 30)); buttonChu.setPreferredSize(new Dimension(55, 30)); buttonDeng.setPreferredSize(new Dimension(55, 30)); buttonDian.setPreferredSize(new Dimension(55, 30)); buttonDel.setPreferredSize(new Dimension(55, 30)); buttonC.setPreferredSize(new Dimension(55, 30));buttonZF.setPreferredSize(new Dimension(55, 30));buttonGH.setPreferredSize(new Dimension(55, 30)); this.add(buttonDel);this.add(buttonC);this.add(buttonZF);this.add(buttonGH);this.add(button1);this.add(button2);this.add(button3);this.add(buttonJia);this.add(button4);this.add(button5);this.add(button6);this.add(buttonJian);this.add(button7);this.add(button8);this.add(button9);this.add(buttonCheng);this.add(button0);this.add(buttonDian);this.add(buttonDeng);this.add(buttonChu);buttonDel.addActionListener(this);buttonC.addActionListener(this);buttonZF.addActionListener(this);buttonGH.addActionListener(this);button1.addActionListener(this);button2.addActionListener(this);button3.addActionListener(this);button4.addActionListener(this);button5.addActionListener(this);button6.addActionListener(this);button7.addActionListener(this);button8.addActionListener(this);button9.addActionListener(this);button0.addActionListener(this);buttonJia.addActionListener(this);buttonJian.addActionListener(this);buttonCheng.addActionListener(this);buttonChu.addActionListener(this);buttonDeng.addActionListener(this);buttonDian.addActionListener(this);// 计算器初始化init();}/*** 计算器初始化*/public void init() {d1 = new BigDecimal("0");d1 = new BigDecimal("0");key = "=";oper = '=';jTextField.setText("0");first = true; // 用于标记是否进行连续操作(例如按键顺序为“9*9====”,第一次等于first由true变为false,如果!first,按等号相当于用上一次的结果与第二个操作数相乘)}/*** 按钮监听*/public void actionPerformed(ActionEvent e) {JButton b = (JButton) e.getSource();if (b == buttonDian) { // 按下.jTextField.setText(jTextField.getText() ".");if (first) {d2 = d1 = getNum();} else {d2 = getNum();}} else if (b == buttonZF) {// 按下±BigDecimal d = getNum();d = new BigDecimal("0").subtract(d);setFormatNum(d);if (first) {d2 = d1 = getNum();} else {d2 = getNum();}} else if (b == buttonDel) {// 按下delif (jTextField.getText().length() == 1|| jTextField.getText().length() == 2&& jTextField.getText().startsWith("-")) { jTextField.setText("0");} else {String s = jTextField.getText();s = s.substring(0, s.length() - 1);if (s.endsWith("E ") || s.endsWith("E-"))s = s.substring(0, s.length() - 2);jTextField.setText(s);if (first) {d2 = d1 = getNum();} else {d2 = getNum();}}} else if (b == buttonC) {// 按下cinit();} else if (b == buttonJia) {// 按下BigDecimal s;if (!first && allKey.indexOf(key) >= 0) {if (oper == '-' || oper == '/') {s = operate(d1, oper, d2);} else {s = operate(d2, oper, d1);}setFormatNum(s);}// 如果不是第一次,且上一次操作是对数字进行操作else {first = false;}d2 = d1 = getNum();// System.out.print("111我执行啦\n");oper = ' ';} else if (b == buttonJian) {// 按下-BigDecimal s;if (!first && allKey.indexOf(key) >= 0) {s = operate(d1, oper, d2);setFormatNum(s);}// 如果不是第一次,且上一次操作是对数字进行操作 else {first = false;}d2 = d1 = getNum();oper = '-';} else if (b == buttonCheng) {// 按下*BigDecimal s;if (!first && allKey.indexOf(key) >= 0) {if (oper == '-' || oper == '/') {s = operate(d1, oper, d2);} else {s = operate(d2, oper, d1);}setFormatNum(s);}// 如果不是第一次,且上一次操作是对数字进行操作 else {first = false;}d2 = d1 = getNum();oper = '*';} else if (b == buttonChu) {// 按下/BigDecimal s;if (!first && allKey.indexOf(key) >= 0) {s = operate(d1, oper, d2);setFormatNum(s);}// 如果不是第一次,且上一次操作是对数字进行操作 else {first = false;}d2 = d1 = getNum();oper = '/';} else if (b == buttonGH) {// 按下平方根if (jTextField.getText().startsWith("-")) {init();return;}BigDecimal d = getNum();MathContext mc = new MathContext(10, RoundingMode.HALF_DOWN);d = new BigDecimal(Math.sqrt(d.doubleValue()), mc);setFormatNum(d);if (first) {d2 = d1 = getNum();} else {d2 = getNum();}} else if (b == buttonDeng) {// 按下=BigDecimal s = null;d2 = getNum();if (!key.equals("=")) {s = operate(d1, oper, d2);} else {s = operate(d2, oper, d1);}if (oper != '=' && !key.equals("=")) {// 上一次操作为 -*/d1 = getNum();}setFormatNum(s);first = true;} else { // 按下其他按钮if (this.jTextField.getText().equals("0")|| allKey.indexOf(key) == -1) {this.jTextField.setText(b.getText());} else {this.jTextField.setText(jTextField.getText()b.getText());}if (first) {d2 = d1 = getNum();} else {d2 = getNum();}// d2作被加数:d2 d1}key = b.getText();}/*** 获取操作数** @return 操作数*/public BigDecimal getNum() {BigDecimal d = new BigDecimal(jTextField.getText());return d;}public void setFormatNum(BigDecimal dd) {MathContext mc = new MathContext(18, RoundingMode.HALF_DOWN);BigDecimal d = new BigDecimal(dd.toString(), mc);String num = d.toString();if (num.endsWith(".0"))num = num.replaceAll("\\.0", "");this.jTextField.setText(num);}/*** 计算** @param a1* 操作数1* @param c* 操作符* @param a2* 操作数2* @return*/public BigDecimal operate(BigDecimal a1, char c, BigDecimal a2) {MathContext mc = new MathContext(10, RoundingMode.HALF_DOWN); switch (c) {case ' ':return a1.add(a2);case '-':return a1.subtract(a2);case '*':return a1.multiply(a2);case '/':if (pareTo(new BigDecimal("0")) == 0) {init();return new BigDecimal("0"); }return a1.divide(a2, mc);default:return a2;}}}}。
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版计算器源代码
jb[3] = new JButton("/");
jb[4] = new JButton(".");
jb[5] = new JButton("sin");
jb[6] = new JButton("cos");
jb[7] = new JButton("tan");
ContaineidLayout gl = new GridLayout(7, 4, 2, 2);
jp1.add(jl);
jp1.add(jt);
jp2.setLayout(gl);
jp2.add(jb[5]);
jp2.add(jb[6]);
setVisible(true);
}
class Lis implements ActionListener {
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
double d = 0.0;
private JButton ok, cancel, C;
private JTextField jt;
private JPanel jp1, jp2;
private JButton[] jb;
private static String str = "";
public Calculator() {
jb[8] = new JButton("aqrt");
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简单计算器代码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、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
b= true;
String s = jv.jtf.getText().trim();
double b = Math.sqrt(Double.parseDouble(s));
jv.jtf.setText(b+"");
}else if(str.equals("+/-")){
jb1.addActionListener(l);
jb2.addActionListener(l);
jb2.setForeground(Color.red);
jb3.addActionListener(l);
jb3.setForeground(Color.red);
jp2 = new JPanel();
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;
JButton jb1, jb2, jb3;
JButton[] jb;
JPanel jp1, jp2, jp3, jp4;
MyActionListener l;
public JsqView(int weith, int heigh) {
Container con = this.getContentPane();
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];
con.setLayout(new BorderLayout(5, 10));
l = new MyActionListener(this);
jtf = new JTextField(26);
jp1 = new JPanel();
jp1.add(jtf);
jtf.setHorizontalAlignment(JTextField.RIGHT);
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);
} catch (MyException e) {
JOptionPane.showMessageDialog(jv, "被除数不能为零","错误",JOptionPane.ERROR_MESSAGE);
return 0;
}
}
num = i / j;
break;
case '%':
num = i % j;
package Swing;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
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);
public class Work1 {
public static void main(String[] args) {
new JsqView(340, 240);
}
}
@SuppressWarnings("serial")
class JsqView extends JFrame {
JTextField jtf;
public MyException(){
super("除数不能为零");
}
}
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;
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();
}
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);
public MyActionListener(JsqView jv) {
this.jv = jv;
}
public void actionPerformed(ActionEvent e) {
String str = e.getActionCommand().trim();
//System.out.println(str);
String[] str = { "7", "8", "9", "/", "sqrt", "4", "5", "6", "*", "%",
"1", "2", "3", "-", "1/x", "0", "+/-", ".", "+", "=" };
for (int i = 0; i < 20; i++) {
this.setVisible(true);
}
}
class MyActionListener implements ActionListener {
JsqView jv;
char operator;
String temp;
Count c = new Count();
boolean b = false;
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) {
jv.jtf.setText("");
} else if (str.equals("=")) {
String s = jv.jtf.getText().trim();
//System.out.println(temp);
//System.out.println(s);
if(""quals(s)||s==null||temp==null){
}
jv.jtf.setText(sbf.toString());
} else if (str.matches("[\\+\\-\\*\\/\\%]")) {
b =false;
operator = str.charAt(0);
//System.out.println(str);
temp = jv.jtf.getText().trim();
}
jp3.add(jp2, BorderLayout.NORTH);