java编写简单计算器源代码
Java编写简单计算器(附源代码)
西安交通大学《Java技术与应用》大作业简单计算器的编写一、选题理由这个学期我选择《Java技术与应用》这门课(其实我的选修课已经修完了),完全是对java语言的兴趣和老师的个人魅力使然。
这门课让我学到了许多知识,了解到了java语言的基本语法、结构和特点。
由于个人觉得水平有限,并且没有队友,所以选择了较为容易的简易计算器作为我的大作业。
二、系统目标实现对代数表达式的输入、计算、输出。
三、系统分析与设计(1)计算类cal设计编写\public class cal {public static boolean check(String str)If Jigloo is being used* commercially (ie, by a corporation, company or business for any purpose* whatever) then you should purchase a license for each developer using Jigloo.* Please visit for details. Use of Jigloo implies* acceptance of these licensing terms. A COMMERCIAL LICENSE HAS NOTBEEN* PURCHASED FOR THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED LEGALLY FOR* ANY CORPORATE OR COMMERCIAL PURPOSE.*/public class NewJFrame extends {》private JTextField jTextField1;private JButton jButton1;private JButton jButton15;private JButton jButton16;private JButton jButton21;private JButton jButton20;private JButton jButton19;private JButton jButton18;private JButton jButton17;private JButton jButton14;?private JButton jButton13;private JButton jButton12;private JButton jButton11;private JButton jButton10;private JButton jButton9;private JButton jButton8;private JButton jButton7;private JButton jButton5;private JButton jButton4;private JButton jButton3;&private JButton jButton2;/*** Auto-generated main method to display this JFrame*/public static void main(String[] args) {(new Runnable() {public void run() {NewJFrame inst = new NewJFrame();(null);\(true);}});}public NewJFrame() {super();initGUI();`}private void initGUI() {try {setDefaultCloseOperation;getContentPane().setLayout(null);("Mycalculation");{jTextField1 = new JTextField();getContentPane().add(jTextField1, "North");)(new 72));(0, 0, 460, 72);(new "Microsoft YaHei UI", 1,16));}{jButton1 = new JButton();getContentPane().add(jButton1);("1");'(25, 87, 82, 48);(new "Microsoft YaHei UI", 0, 18));(new ActionListener() {public void actionPerformed(ActionEvent evt) {", event="+ evt);dd(jButton2);("2");(120, 87, 82, 48);(new "Microsoft YaHei UI", 0, 18));)(new ActionListener() {public void actionPerformed(ActionEvent evt) {", event="dd(jButton3);("3");(214, 87, 82, 48);(new "Microsoft YaHei UI", 0, 18));(new ActionListener() {|public void actionPerformed(ActionEvent evt) {", event="+ evt);dd(jButton4);("4");(25, 142, 82, 48);(new "Microsoft YaHei UI", 0, 18));(new ActionListener() {public void actionPerformed(ActionEvent evt) {", event="`+ evt);dd(jButton5);("5");(122, 142, 82, 48);(new "Microsoft YaHei UI", 0, 18));(new ActionListener() {public void actionPerformed(ActionEvent evt) {", event="+ evt);dd(jButton7);!("6");(215, 142, 82, 48);(new "Microsoft YaHei UI", 0, 18));(new ActionListener() {public void actionPerformed(ActionEvent evt) {", event="+ evt);dd(jButton8);("7");(26, 201, 82, 50);¥(new "Microsoft YaHei UI", 0, 18));(new ActionListener() {public void actionPerformed(ActionEvent evt) {", event="dd(jButton9);("8");(122, 201, 82, 50);(new "Microsoft YaHei UI", 0, 18));(new ActionListener() {|public void actionPerformed(ActionEvent evt) {", event="+ evt);dd(jButton10);("9");(215, 201, 82, 50);jButton10.setFont(new "Microsoft YaHei UI", 0, 18));(new ActionListener() {public void actionPerformed(ActionEvent evt) { @", event="+ evt);dd(jButton11);("0");(26, 269, 82, 48);jButton11.setFont(new "Microsoft YaHei UI", 0, 18));(new ActionListener() {public void actionPerformed(ActionEvent evt) {", event="~+ evt);dd(jButton12);("+");(309, 147, 64, 45);jButton12.setFont(new "Microsoft YaHei UI", 0, 28));(new ActionListener() {public void actionPerformed(ActionEvent evt) {", event="+ evt);—dd(jButton13);("-");(384, 148, 64, 44);jButton13.setFont(new "Microsoft YaHei UI", 0, 28));(new ActionListener() {public void actionPerformed(ActionEvent evt) {", event="+ evt);dd(jButton14);…("*");(309, 208, 64, 44);jButton14.setFont(new "Microsoft YaHei UI", 0, 28));(new ActionListener() {public void actionPerformed(ActionEvent evt) {", event="+ evt);dd(jButton15);("/");!(384, 208, 64, 44);jButton15.setFont(new "Microsoft YaHei UI", 0, 28));(new ActionListener() {public void actionPerformed(ActionEvent evt) {", event="+ evt);dd(jButton16);("=");(386, 271, 64, 44);/jButton16.setFont(new "Microsoft YaHei UI", 0, 28));(new ActionListener() {public void actionPerformed(ActionEvent evt) {", event="+ evt);dd(jButton17);("^");(311, 271, 64, 44);jButton17\.setFont(new "Microsoft YaHei UI", 0, 28));(new ActionListener() {public void actionPerformed(ActionEvent evt) {", event="+ evt);dd(jButton18);("C");(215, 271, 82, 48);jButton18.setFont(new "Microsoft YaHei UI", 0, 18));…(new ActionListener() {public void actionPerformed(ActionEvent evt) {", event="+ evt);dd(jButton19);(")");(384, 93, 64, 44);jButton19.setFont(new "Microsoft YaHei UI", 0, 28));(new ActionListener() {~public void actionPerformed(ActionEvent evt) {", event="+ evt);dd(jButton20);("(");(308, 93, 64, 44);jButton20.setFont(new "Microsoft YaHei UI", 0, 28));(new ActionListener() {public void actionPerformed(ActionEvent evt) { !", event="+ evt);dd(jButton21);(".");(122, 270, 82, 48);jButton21.setFont(new "Microsoft YaHei UI", 0, 28));(new ActionListener() {public void actionPerformed(ActionEvent evt) {", event="》+ evt);||(i)>=48&&(i)<=57))continue;else{(null, "输入错误!");return bool;}}||(i)!=')')&&(i+1)=='(')||(i)==')'&&(i+1)!='('||(i+1)=='.'))){}.else{(null, "输入错误!");return bool;}}elsebreak;i++;}if(num1==num2){bool=true;}:else (null, "输入错误!");return bool;}||(i)=='0'||(i)=='1'||(i)=='2'||(i)=='3'||(i)=='4'||(i)=='5'||(i)=='6'||(i)=='7'||(i)=='8'||(i)=='9'){str2=str2+(i);continue;}else{·if(str2!=""){//如果str2不为空,既之前有扫描到数字,则进行压栈(str2));//str2还原str2="";}//比较当前元素(其实为一操作符)与操作符栈中的栈顶元素的优先级for(;;){//如果当前元素的优先级低于或等于栈顶元素的优先级if(compare(i),())){*float temp;//做如下操作switch()){//栈顶元素为+,弹出数字栈的前两个元素,进行运算case '+':temp=()+();(temp);//弹出操作符栈中用过的元素();break;.//栈顶元素为-,弹出数字栈的前两个元素,进行运算case '-':temp=()+();(temp);//弹出操作符栈中用过的元素();break;//栈顶元素为*,弹出数字栈的前两个元素,进行运算case '*':temp=()*();;(temp);//弹出操作符栈中用过的元素();break;//栈顶元素为/,弹出数字栈的前两个元素,进行运算case '/':temp=1/()*();(temp);//弹出操作符栈中用过的元素();|break;//栈顶元素为^,弹出数字栈的前两个元素,进行运算case '^':float n=();float e=();temp=(float) (e,n);// (temp);//弹出操作符栈中用过的元素();break;~//栈顶元素为(,不进行任何运算case '('://只有当当前元素为“)”时,才弹出“(”,否则,将当前元素压栈,//并进行下一次循环,即扫描字符串的下一个元素if(i)==')'){//弹出操作符栈中用过的元素();continue loop;}else{¥(i));continue loop;}}}else{// “)” 不入栈if(i)!=')')(i));break;}}}}//返回栈顶元素,即算式结果return ();}//比较优先级,判断b的优先级是否大于等于a的优先级public static boolean compare(char a,char b){boolean bool=false;if(a=='#')bool=true;elseif(a=='$'&&b!='#')bool=true;elseif(a==')'&&b!='#'&&b!='$')bool=true;elseif((a=='+'||a=='-')&&(b=='+'||b=='-'||b=='*'||b=='/'||b=='^'||b=='('))bool=true;elseif((a=='*'||a=='/')&&(b=='*'||b=='/'||b=='^'||b=='('))bool=true;elseif((a=='^')&&(b=='^'||b=='('))bool=true;elseif(a=='('&&b=='(')bool=true;return bool;} }?。
用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编写的计算器源代码
package jsq;import java.awt.Color;import java.awt.GridLayout;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.WindowEvent;import java.awt.event.WindowListener;import javax.swing.ImageIcon;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JMenu;import javax.swing.JMenuBar;import javax.swing.JMenuItem;import javax.swing.JOptionPane;import javax.swing.JPanel;import javax.swing.JTextField;import javax.swing.UIManager;public class Test implements ActionListener {/****/JFrame f = new JFrame();JTextField tf = new JTextField("0.");JMenuBar bar=new JMenuBar();JMenu menuEdit=new JMenu("编辑(E)");JMenu menuView=new JMenu("查看(V)");JMenu menuHelp=new JMenu("帮助(H)");JMenuItem menuEditCopy=new JMenuItem("复制(C)");JMenuItem menuEditPaste=new JMenuItem("粘贴(V)");JMenuItem menuHelpAbout = new JMenuItem("关于计算器(A)");JPanel panel0 = new JPanel();JPanel panel2 = new JPanel();JPanel panel = new JPanel();JPanel panel3 = new JPanel();JPanel panel4 = new JPanel();JPanel panel5 = new JPanel();JButton btBk = new JButton(" Backspace"); JButton btCe = new JButton("Ce");JButton btCl = new JButton("C");JButton bt7 = new JButton("7");JButton bt8 = new JButton("8");JButton bt9 = new JButton("9");JButton btDiv = new JButton("/");JButton btSqrt = new JButton("sqrt");JButton bt4 = new JButton("4");JButton bt5 = new JButton("5");JButton bt6 = new JButton("6");JButton btMult = new JButton("*"); JButton btMol = new JButton(" % ");JButton bt1 = new JButton("1");JButton bt2 = new JButton("2");JButton bt3 = new JButton("3");JButton btMinu = new JButton("-"); JButton btCoun = new JButton(" 1/x");JButton bt0 = new JButton("0");JButton btPoint = new JButton("."); JButton btEqual = new JButton("="); JButton btAdd = new JButton("+");JButton btSign = new JButton(" +/-");/***@param args*/public void init(){f.add(panel0);f.add(tf,"North");f.setJMenuBar(bar);bar.add(menuEdit);bar.add(menuView);bar.add(menuHelp);menuEdit.add(menuEditCopy);menuEdit.add(menuEditPaste);menuHelp.add(menuHelpAbout);tf.setEditable(false);//不可编辑tf.setHorizontalAlignment(JTextField.RIGHT);//从右侧输入数据panel0.add(panel2);panel0.add(panel);panel0.add(panel3);panel0.add(panel4);panel0.add(panel5);panel2.setLayout(new GridLayout(1,4));panel2.add(btBk);panel2.add(btCe);panel2.add(btCl);panel.setLayout(new GridLayout(1,5));panel.add(bt7);panel.add(bt8);panel.add(bt9);panel.add(btDiv);panel.add(btSqrt);//根号panel3.setLayout(new GridLayout(1,5));panel3.add(bt4);panel3.add(bt5);panel3.add(bt6);panel3.add(btMult);panel3.add(btMol);//百分号panel4.setLayout(new GridLayout(1,5));panel4.add(bt1);panel4.add(bt2);panel4.add(bt3);panel4.add(btMinu);panel4.add(btCoun);//倒数panel5.setLayout(new GridLayout(1,5));panel5.add(bt0);panel5.add(btPoint);panel5.add(btAdd);panel5.add(btEqual);panel5.add(btSign);//正负符号btBk.setForeground(new Color(255, 0, 0)); btCe.setForeground(new Color(255, 0, 0)); btCl.setForeground(new Color(255, 0, 0)); btAdd.setForeground(new Color(255, 0, 0)); btMult.setForeground(new Color(255, 0, 0)); btDiv.setForeground(new Color(255, 0, 0)); btMinu.setForeground(new Color(255, 0, 0)); btEqual.setForeground(new Color(255, 0, 0));bt0.setForeground(new Color(0,0,255));bt1.setForeground(new Color(0, 0, 255));bt2.setForeground(new Color(0,0,255));bt3.setForeground(new Color(0,0,255));bt4.setForeground(new Color(0,0,255));bt5.setForeground(new Color(0,0,255));bt6.setForeground(new Color(0,0,255));bt7.setForeground(new Color(0,0,255));bt8.setForeground(new Color(0,0,255));bt9.setForeground(new Color(0,0,255)); btSqrt.setForeground(new Color(0,0,255)); btMol.setForeground(new Color(0,0,255)); btCoun.setForeground(new Color(0,0,255)); btSign.setForeground(new Color(0,0,255));//注册监听bt1.addActionListener(this);bt2.addActionListener(this);bt3.addActionListener(this);bt4.addActionListener(this);bt5.addActionListener(this);bt6.addActionListener(this);bt7.addActionListener(this);bt8.addActionListener(this);bt9.addActionListener(this);bt0.addActionListener(this);btAdd.addActionListener(this);btMinu.addActionListener(this);btMult.addActionListener(this);btDiv.addActionListener(this);btEqual.addActionListener(this);btPoint.addActionListener(this);btSqrt.addActionListener(this);btMol.addActionListener(this);btCoun.addActionListener(this);btSign.addActionListener(this);btBk.addActionListener(this);btCe.addActionListener(this);btCl.addActionListener(this);menuEditCopy.addActionListener(this);menuEditPaste.addActionListener(this);menuHelpAbout.addActionListener(this);f.addWindowListener(new MyWinLis());f.setTitle("计算器");f.setSize(295,240);f.setResizable(false);//不能改变窗体大小f.setVisible(true);}String foreNum=null;String currOpr=null;String currNum=null;boolean i = true;String copy;//复制public void actionPerformed(ActionEvent e) {// TODO自动生成方法存根Object obj=e.getSource();//输入数字if(obj==bt1||obj==bt2||obj==bt3||obj==bt4||obj==bt5||obj==bt6||obj==bt7||obj== bt8||obj==bt9||obj==bt0){if(i==true)tf.setText(e.getActionCommand());elsetf.setText(tf.getText()+e.getActionCommand());i = false;}//小数点else if(obj==btPoint){if(i==false)tf.setText(tf.getText()+'.');}//实现开根号else if(obj==btSqrt){if(tf.getText().charAt(0)=='-'){tf.setText("函数输入无效");}elsetf.setText(Double.toString(ng.Math.sqrt(Double. parseDouble(tf.getText()))));i = true;}//实现倒数else if(obj==btCoun){if (tf.getText().charAt(0) == '0') {tf.setText("零不能求倒数");i = true;}else {String s = Double.toString(1 / Double.parseDouble(tf.getText()));foreNum = tf.getText();tf.setText(s);i = true;}}//实现+/-符号else if (obj == btSign) {boolean isNumber = true;String s = tf.getText();for (int m = 0; m< s.length(); m++)if (! (s.charAt(m) >= '0' && s.charAt(m) <='9' || s.charAt(m) =='.'||s.charAt(m) == '-')) {break;}if (isNumber == true) {//如果当前字符串首字母有-号,代表现在是个负数,再按下时,则将首符号去掉if (s.charAt(0) == '-') {tf.setText("");for (int m = 1; m< s.length(); m++) {char a = s.charAt(m);tf.setText(tf.getText() + a);}}//如果当前字符串第一个字符不是符号,则添加一个符号在首字母处elsetf.setText('-' + s);}}//实现%功能else if(obj==btMol){boolean isNumber = true;if(isNumber==true)tf.setText(String.valueOf(Double.parseDouble(tf.getText())/100));elsetf.setText("错误");}//实现符号运算else if(obj==btAdd||obj==btMinu||obj==btDiv||obj==btMult){if(i==false){currNum=tf.getText();if(currOpr=="+")tf.setText(String.valueOf(Double.parseDouble(foreNum)+Double.parseDouble(currN um)));else if(currOpr=="-")tf.setText(String.valueOf(Double.parseDouble(foreNum)-Double.parseDouble(currN um)));else if(currOpr=="*")tf.setText(String.valueOf(Double.parseDouble(foreNum)*Double.parseDouble(currN um)));else if(currOpr=="/"){if (Double.parseDouble(tf.getText()) == 0)tf.setText("除数不能为零");elsetf.setText(String.valueOf(Double.parseDouble(foreNum)/Double.parseDouble(currNum))) ;}}foreNum=tf.getText();tf.setText("");currOpr=e.getActionCommand();i = false;}//实现等号else if(obj==btEqual){currNum=tf.getText();if(currOpr=="+")tf.setText(String.valueOf(Double.parseDouble(foreNum)+Double.parseDouble(currN um)));else if(currOpr=="-")tf.setText(String.valueOf(Double.parseDouble(foreNum)-Double.parseDouble(currN um)));else if(currOpr=="*")tf.setText(String.valueOf(Double.parseDouble(foreNum)*Double.parseDouble(currN um)));else if(currOpr=="/"){if (Double.parseDouble(tf.getText()) == 0)tf.setText("除数不能为零");elsetf.setText(String.valueOf(Double.parseDouble(foreNum)/Double.parseDouble(currN um)));}currOpr=e.getActionCommand();i = true;}//实现Backspace功能else if(obj==btBk){String s = tf.getText();tf.setText("");for (int m = 0;m <s.length() - 1; m++) {char a = s.charAt(m);tf.setText(tf.getText() + a);i = true;}}//实现Ce功能else if (obj == btCe) {tf.setText("0.");}//实现C功能else if (obj == btCl) {foreNum=currNum="";tf.setText("0.");}//实现复制else if(obj==menuEditCopy){copy=tf.getText();}//实现粘贴else if (obj == menuEditPaste) {tf.setText(copy);}//实现帮助主题else if(obj == menuHelpAbout){ImageIcon icon = new ImageIcon("src//Icons//about1.jpg");JLabel label = new JLabel(icon);JOptionPane.showMessageDialog(f,label,"帮助主题",JOptionPane.PLAIN_MESSAGE);}}public static void main(String[] args) {// TODO自动生成方法存根try{UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());//UIManager统一管理}catch(Exception e) {e.printStackTrace();}Test t = new Test();t.init();}}class MyWinLis implements WindowListener{public void windowActivated(WindowEvent arg0) {// TODO自动生成方法存根}public void windowClosed(WindowEvent arg0) { // TODO自动生成方法存根}public void windowClosing(WindowEvent arg0) { // TODO自动生成方法存根System.exit(0);}public void windowDeactivated(WindowEvent arg0) { // TODO自动生成方法存根}public void windowDeiconified(WindowEvent arg0) { // TODO自动生成方法存根}public void windowIconified(WindowEvent arg0) { // TODO自动生成方法存根}public void windowOpened(WindowEvent arg0) { // TODO自动生成方法存根}}。
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.*;class ComputerExe extends Frame implements ActionListener {Button b1,b2,b3,b4;TextField t1,t2,t3;Label l1,l2;public static void main(String[] args)//程序入口{new ComputerExe();//创建本窗体对象}ComputerExe()//构造方法{super("四则运算");setBounds(100,100,300,200);setVisible(true);b1=new Button("加");b2=new Button("减");b3=new Button("乘");b4=new Button("除");t1=new TextField(15);t2=new TextField(15);t3=new TextField(15);l1=new Label("");l2=new Label("=");l1.setBackground(Color.yellow);l1.setForeground(Color.red);l2.setBackground(Color.yellow);l2.setForeground(Color.red);t3.setEditable(false);setLayout(new FlowLayout());//更改窗体框架的布局add(t1);add(l1);add(t2);add(l2);add(t3);add(b1);add(b2);add(b3);add(b4);setVisible(true);b1.addActionListener(this);b2.addActionListener(this);b3.addActionListener(this);b4.addActionListener(this);}//构造方法结束public void actionPerformed(ActionEvent e) { double n1,n2,n3;if(e.getSource()==b1){try{n1=Double.parseDouble(t1.getText());n2=Double.parseDouble(t2.getText());n3=n1+n2;t3.setText(String.valueOf(n3));l1.setText("+");}catch(NumberFormatException w){t3.setText("操作数应该为数字!");}}if(e.getSource()==b2){try{n1=Double.parseDouble(t1.getText());n2=Double.parseDouble(t2.getText());n3=n1-n2;t3.setText(String.valueOf(n3));l1.setText("-");}catch(NumberFormatException w){t3.setText("操作数应该为数字!");}}if(e.getSource()==b3){try{n1=Double.parseDouble(t1.getText());n2=Double.parseDouble(t2.getText());n3=n1*n2;t3.setText(String.valueOf(n3));l1.setText("*");}catch(NumberFormatException w){t3.setText("操作数应该为数字!");}}if(e.getSource()==b4){try{n1=Double.parseDouble(t1.getText());n2=Double.parseDouble(t2.getText());n3=n1/n2;t3.setText(String.valueOf(n3));l1.setText("/");}catch(NumberFormatException w){t3.setText("操作数应该为数字!");}}}}//类结束。
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语言写的计算器源代码附解析
//把代码改成Calc.java编译运行,完整版计算器,最下面是计算器界面import java.awt.*;import java.awt.event.*;public class Calc extends WindowAdapter implements ActionListener, MouseListener{Color cMoveOut=new Color(240 ,240 ,240);Color cMoveIn =new Color( 255,255,55);//状态变量boolean clicked=true;//判断是否单击了小数点boolean clear=true;//判断是否单击了符号位double previous;//记录第一个操作数double next;//记录第二个操作数String fuhao;//记录符号位int first=1;//标记是否开始一次新的运算过程Frame f;Panel p1,p2;TextField tf;Font fnt;Button b1,b2,b3,b4,b5,b6,b7,b8,b9,b0;Button bDiv,bSqrt,bMulti,bMinus,bPercent,bPlus,bReciprocal,bEqual,bDot,bNegative,bBack;Button bPingFang , bDaoShu , bSin, bCos ,bTan;Button bC;GridLayout p2Layout;public void display(){f=new Frame("计算器");f.setSize(280,213);f.setLocation(200,200);f.setBackground(Color.LIGHT_GRAY);f.setResizable(false);p1=new Panel(new FlowLayout());tf=new TextField(35);tf.setText("0.");tf.setEditable(false);p1.add(tf);f.add(p1,BorderLayout.NORTH);p2Layout=new GridLayout(5,5,5,4);p2=new Panel(p2Layout);f.add(p2,BorderLayout.CENTER);fnt=new Font("Serief",Font.BOLD,20);b1=new Button("1");b1.setFont(fnt);b2=new Button("2");b2.setFont(fnt);b3=new Button("3");b3.setFont(fnt);b4=new Button("4");b4.setFont(fnt);b5=new Button("5");b5.setFont(fnt);b6=new Button("6");b6.setFont(fnt);b7=new Button("7");b7.setFont(fnt);b8=new Button("8");b8.setFont(fnt);b7.setFont(fnt);b9=new Button("9");b9.setFont(fnt);b0=new Button("0");b0.setFont(fnt);b9.setFont(fnt);bPingFang=new Button("^2"); bPingFang.setFont(fnt); bDaoShu=new Button("1/X"); bDaoShu.setFont(fnt);bSin=new Button("sin");bSin.setFont(fnt);bCos=new Button("cos"); bCos.setFont(fnt);bTan=new Button("tan"); bTan.setFont(fnt);b1.addActionListener(this);b2.addActionListener(this);b3.addActionListener(this);b4.addActionListener(this);b5.addActionListener(this);b6.addActionListener(this);b7.addActionListener(this);b8.addActionListener(this);b9.addActionListener(this);b0.addActionListener(this); bBack=new Button("Back");//退格bBack.setFont(fnt);bC=new Button("C");//清空bC.setFont(fnt);bDiv=new Button("/");bDiv.setFont(fnt);bSqrt=new Button("sqrt"); bSqrt.setFont(fnt);bMulti=new Button("*"); bMulti.setFont(fnt);bMinus=new Button("-"); bMinus.setFont(fnt);bPercent=new Button("%"); bPercent.setFont(fnt);bPlus=new Button("+"); bPlus.setFont(fnt);bEqual=new Button("="); bEqual.setFont(fnt);bDot=new Button(".");bDot.setFont(fnt);bNegative=new Button("+/-"); bNegative.setFont(fnt); bBack.addActionListener(this);bC.addActionListener(this); bDiv.addActionListener(this); bSqrt.addActionListener(this); bPingFang.addActionListener(this); bPercent.addActionListener(this); bDaoShu.addActionListener(this); bMulti.addActionListener(this); bPlus.addActionListener(this); bMinus.addActionListener(this); bMulti.addActionListener(this); bDiv.addActionListener(this); bSin.addActionListener(this); bCos.addActionListener(this); bTan.addActionListener(this); bEqual.addActionListener(this); bDot.addActionListener(this); bNegative.addActionListener(this); bSqrt.addMouseListener(this); bPingFang.addMouseListener(this); bPercent.addMouseListener(this); bC.addMouseListener(this); bBack.addMouseListener(this);b7.addMouseListener(this);b8.addMouseListener(this);b9.addMouseListener(this); bDiv.addMouseListener(this); bDaoShu.addMouseListener(this); b4.addMouseListener(this);b5.addMouseListener(this);b6.addMouseListener(this); bMulti.addMouseListener(this); bSin.addMouseListener(this);b1.addMouseListener(this);b2.addMouseListener(this);b3.addMouseListener(this); bMinus.addMouseListener(this); bCos.addMouseListener(this);b0.addMouseListener(this); bDot.addMouseListener(this); bEqual.addMouseListener(this); bPlus.addMouseListener(this); bTan.addMouseListener(this);p2.add(bSqrt);p2.add(bPingFang);p2.add(bPercent);p2.add(bC);p2.add(bBack);p2.add(b7);p2.add(b8);p2.add(b9);p2.add(bDiv);p2.add(bDaoShu);p2.add(b4);p2.add(b5);p2.add(b6);p2.add(bMulti);p2.add(bSin);p2.add(b1);p2.add(b2);p2.add(b3);p2.add(bMinus);p2.add(bCos);p2.add(b0);p2.add(bDot);p2.add(bEqual);p2.add(bPlus);p2.add(bTan);f.setV isible(true);f.addWindowListener(this);}public void actionPerformed(ActionEvent e) {if (first ==1)tf.setText("");first=0;Object temp=e.getSource();//退格if (temp== bBack){String s=tf.getText();tf.setText("");for (int i=0;i<s.length()-1;i++){char a=s.charAt(i);tf.setText(tf.getText()+a);}}//清零if (temp==bC){tf.setText("0.");clear=true;first=1;}if (temp==b0){//判断是否单击了符号位if (clear==false)tf.setText("");tf.setText(tf.getText()+"0");}if (temp==b1){if (clear==false)tf.setText("");tf.setText(tf.getText()+"1");clear=true;}if (temp==b2){if (clear==false)tf.setText("");tf.setText(tf.getText()+"2");clear=true;}if (temp==b3){if (clear==false)tf.setText("");tf.setText(tf.getText()+"3");clear=true;}if (temp==b4){if (clear==false)tf.setText("");tf.setText(tf.getText()+"4");clear=true;}if (temp==b5){if (clear==false)tf.setText("");tf.setText(tf.getText()+"5");clear=true;}if (temp==b6){if (clear==false)tf.setText("");tf.setText(tf.getText()+"6");clear=true;}if (temp==b7){if (clear==false)tf.setText("");tf.setText(tf.getText()+"7");clear=true;}if (temp==b8){if (clear==false)tf.setText("");tf.setText(tf.getText()+"8");clear=true;}if (temp==b9){if (clear==false)tf.setText("");tf.setText(tf.getText()+"9");clear=true;}//判断是否含有小数点if (temp == bDot){clicked=true;for (int i=0;i<tf.getText().length();i++)if ('.'==tf.getText().charAt(i)){clicked = false;break;}if (clicked == true){tf.setText(tf.getText()+".");clear=true;}}//bSqrtif(temp == bSqrt){tf.setText( Math.sqrt( Double.parseDouble(tf.getText())) + "" );clear=false;}//bPingFangif(temp == bPingFang ){tf.setText( Math.pow( Double.parseDouble(tf.getText() ), 2 ) + "" );clear=false;}//倒数if(temp == bDaoShu){tf.setText( 1 / Double.parseDouble(tf.getText()) + "" );clear =false;}//Sinif(temp == bSin){tf.setText( Math.sin( Math.toRadians( Double.parseDouble( tf.getText() ) ) ) + "" );clear =false;}//Cosif(temp == bCos){tf.setText( Math.cos( Math.toRadians( Double.parseDouble( tf.getText() ) ) ) + "" );clear =false;}//tanif(temp == bTan){tf.setText( Math.tan( Math.toRadians( Double.parseDouble( tf.getText() ) ) ) + "");clear =false;}//加法运算if (temp==bPlus){previous=Double.parseDouble(tf.getText());fuhao="+";clear=false;//System.out.print("+");}//减法运算if (temp == bMinus){previous=Double.parseDouble(tf.getText());fuhao="-";clear=false;}//乘法运算if (temp == bMulti){previous=Double.parseDouble(tf.getText());fuhao="*";clear=false;}//除法运算bDivif (temp == bDiv){previous=Double.parseDouble(tf.getText());fuhao="/";clear=false;}//求余数if(temp == bPercent){previous=Double.parseDouble( tf.getText());fuhao="%";clear=false;}//等于if (temp==bEqual){try{next = Double.parseDouble(tf.getText());tf.setText("");if (fuhao =="+")tf.setText(previous + next +"");if(fuhao == "-")tf.setText(previous - next +"");if(fuhao == "*")tf.setText(previous * next +"");if(fuhao == "/")tf.setText(previous / next +"");if(fuhao == "%")tf.setText(previous % next +"");clear=false;}catch(Exception ex){tf.setText("请检查输入的数据:" + ex.getMessage()) ;clear=false;}}}public void mouseEntered(MouseEvent e){Object temp= e.getSource();if(temp==bPingFang){//System.out.println( bBack.getBackground() );bPingFang.setBackground(cMoveIn);}if(temp==bSqrt){bSqrt.setBackground(cMoveIn);}if(temp==bPercent){bPercent.setBackground(cMoveIn);}if(temp==bC){bC.setBackground(cMoveIn);}if(temp==bBack){bBack.setBackground(cMoveIn);}if(temp==b7){b7.setBackground(cMoveIn);}if(temp==b8){b8.setBackground(cMoveIn);}if(temp==b9){b9.setBackground(cMoveIn);}if(temp==bDiv){bDiv.setBackground(cMoveIn);}if(temp==bDaoShu){bDaoShu.setBackground(cMoveIn); }if(temp==b4){b4.setBackground(cMoveIn);}if(temp==b5){b5.setBackground(cMoveIn);}if(temp==b6){b6.setBackground(cMoveIn);}if(temp==bMulti){bMulti.setBackground(cMoveIn); }if(temp==bSin){bSin.setBackground(cMoveIn);}if(temp==b1){b1.setBackground(cMoveIn);}if(temp==b2){b2.setBackground(cMoveIn);}if(temp==b3){b3.setBackground(cMoveIn);}if(temp==bMinus){bMinus.setBackground(cMoveIn); }if(temp==bCos){bCos.setBackground(cMoveIn);}if(temp==b0){b0.setBackground(cMoveIn);}if(temp==bDot){bDot.setBackground(cMoveIn);}if(temp==bEqual){bEqual.setBackground(cMoveIn);}if(temp==bPlus){bPlus.setBackground(cMoveIn);}if(temp==bTan){bTan.setBackground(cMoveIn);}}public void mouseExited(MouseEvent e) {Object temp= e.getSource();if(temp==bPingFang){//System.out.println( bBack.getBackground() );bPingFang.setBackground(cMoveOut);}if(temp==bSqrt){bSqrt.setBackground(cMoveOut);}if(temp==bPercent){bPercent.setBackground(cMoveOut);}if(temp==bC){bC.setBackground(cMoveOut);}if(temp==bBack){bBack.setBackground(cMoveOut);}if(temp==b7){b7.setBackground(cMoveOut);}if(temp==b8){b8.setBackground(cMoveOut);}if(temp==b9){b9.setBackground(cMoveOut);}if(temp==bDiv){bDiv.setBackground(cMoveOut);}if(temp==bDaoShu){bDaoShu.setBackground(cMoveOut); }if(temp==b4){b4.setBackground(cMoveOut);}if(temp==b5){b5.setBackground(cMoveOut);}if(temp==b6){b6.setBackground(cMoveOut);}if(temp==bMulti){bMulti.setBackground(cMoveOut); }if(temp==bSin){bSin.setBackground(cMoveOut);}if(temp==b1){b1.setBackground(cMoveOut);}if(temp==b2){b2.setBackground(cMoveOut);}if(temp==b3){b3.setBackground(cMoveOut);}if(temp==bMinus){bMinus.setBackground(cMoveOut); }if(temp==bCos){bCos.setBackground(cMoveOut);}if(temp==b0){b0.setBackground(cMoveOut);}if(temp==bDot){bDot.setBackground(cMoveOut);}if(temp==bEqual){bEqual.setBackground(cMoveOut);}if(temp==bPlus){bPlus.setBackground(cMoveOut);}if(temp==bTan){bTan.setBackground(cMoveOut);}}public static void main(String args[]){Calc frame=new Calc();frame.display();}public void windowClosing(WindowEvent e){System.exit(0);}public void mouseClicked(MouseEvent arg0) {}public void mousePressed(MouseEvent arg0) {}public void mouseReleased(MouseEvent arg0) { }}。
超级简单明了的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计算器源代码
计算器源代码一、计算器源代码文件名: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);}}二、计算器界面三、修改后计算器界面。
简单的计算器源代码
//计算器,已经编译通过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简易计算器完整代码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简单计算器代码:```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简单计算器代码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)。
import javax.swing.*;import java.awt.event.*;import java.awt.*;import ng.Math;class ring extends JFrame implements ActionListener{//定义成员变量://JFrame frame;//定义一个窗口类;JTextField text;//定义一个文本框类;JLabel label;//定义一个标签类;JPanel p1,p2,p3,p4,p5,p6;//定义面板类;String s1,s,s2;//定义三个字符串变量;int count=0;JButtona1,a2,a3,a4,a5,a6,b1,b2,b3,b4,b5,b6,c1,c2,c3,c4,c5,c6,d1,d2,d3,d4 ,d5,d6;//ring的构造函数;ring(){this.setTitle("计算器");// super("计算器");JMenuBar menubar1=new JMenuBar();//新建菜单条;this.setJMenuBar(menubar1);JMenu menu1=new JMenu("编辑(E)");JMenu menu2=new JMenu("查看(V)");JMenu menu3=new JMenu("帮助(H)");menubar1.add(menu1);menubar1.add(menu2);menubar1.add(menu3);JMenuItem item1=new JMenuItem("复制(c) ctrl+c");JMenuItem item2=new JMenuItem("粘贴(p) ctrl+v");JMenuItem item3=new JMenuItem("标准型(T)");JMenuItem item4=new JMenuItem("科学型(s)");JMenuItem item5=new JMenuItem("数字分组(I)");JMenuItem item6=new JMenuItem("帮助主题(H)");JMenuItem item7=new JMenuItem("关于计算机(A)");menu1.add(item1);menu1.add(item2);menu2.add(item3);menu2.add(item4);menu2.add(item5);menu3.add(item6);menu3.add(item7);this.show();this.setBounds(100,100,500,100);this.setVisible(true);p1=new JPanel();//新建面板对象;label=new JLabel("计算结果");//新建一个“计算结果”的标签;text=new JTextField(25);//定义25字符的文档框;text.setEditable(false);text.setHorizontalAlignment(JTextField.LEFT);//定义水平左对齐;p1.add(label);//将标签label添加到面板p1中;p1.add(text);//将文本框text添加到面板p1中;a1=new JButton("Backspace");a2=new JButton("7");a3=new JButton("8");a4=new JButton("9");a5=new JButton("/");a6=new JButton("sqrt");b1=new JButton("MR");b2=new JButton("4");b3=new JButton("5");b4=new JButton("6");b5=new JButton("*");b6=new JButton("%");c1=new JButton("MS");c2=new JButton("1");c3=new JButton("2");c4=new JButton("3");c5=new JButton("-");c6=new JButton("1/x");d1=new JButton("M+");d2=new JButton("0");d3=new JButton("+/-");d4=new JButton(".");d5=new JButton("+");d6=new JButton("=");JPanel p=new JPanel(new GridLayout(4,6,10,10));p.add(a1);p.add(a2);p.add(a3);p.add(a4);p.add(a5);p.add(a6);p.add(b1);p.add(b2);p.add(b3);p.add(b4);p.add(b5);p.add(b6);p.add(c1);p.add(c2);p.add(c3);p.add(c4);p.add(c5);p.add(c6);p.add(d1);p.add(d2);p.add(d3);p.add(d4);p.add(d5);p.add(d6);add(p1);add(p,BorderLayout.SOUTH);//将面板p添加到窗口中;并指定面板p位于底部;//为按钮注册监听器;a1.addActionListener(this);a2.addActionListener(this);a3.addActionListener(this);a4.addActionListener(this);a5.addActionListener(this);a6.addActionListener(this);b1.addActionListener(this);b2.addActionListener(this);b3.addActionListener(this);b4.addActionListener(this);b5.addActionListener(this);b6.addActionListener(this);c1.addActionListener(this);c2.addActionListener(this);c3.addActionListener(this);c4.addActionListener(this);c5.addActionListener(this);c6.addActionListener(this);d1.addActionListener(this);d2.addActionListener(this);d3.addActionListener(this);d4.addActionListener(this);d5.addActionListener(this);d6.addActionListener(this);}public void actionPerformed(ActionEvent e){String str=e.getActionCommand();if(str.equals("7")){text.setText( text.getText()+"7");}else if(str.equals("8")){text.setText(text.getText()+"8");}else if(str.equals("9")){text.setText(text.getText()+"9");}else if(str.equals("4")){text.setText(text.getText()+"4");}else if(str.equals("5")){text.setText(text.getText()+"5");}else if(str.equals("6")){text.setText(text.getText()+"6");}else if(str.equals("1")){text.setText(text.getText()+"1");}else if(str.equals("2")){text.setText(text.getText()+"2");}else if(str.equals("3")){text.setText(text.getText()+"3");}else if(str.equals("0")){text.setText(text.getText()+"0");}else if(str.equals(".")){text.setText(text.getText()+"."); }else if(str.equals("+/-")){count++;if(count%2==0){text.setText("+"+text.getText());}elsetext.setText("-"+text.getText());}else if(str.equals("Backspace")){text.setText("");}else if(str.equals("+")){s1=text.getText();s="+";text.setText("");}else if(str.equals("-")){s1=text.getText();s="-";text.setText("");}else if(str.equals("*")){s1=text.getText();s="*";text.setText("");}else if(str.equals("/")){s1=text.getText();s="/";text.setText("");}else if(str.equals("1/x")){s1=text.getText();s="1/x";text.setText("");double num11=Double.parseDouble(s1);double ans=0;ans=1/num11;text.setText(ans+"");}else if(str.equals("sqrt")){s1=text.getText();s="sqrt";text.setText("");double num11=Double.parseDouble(s1);double ans=0;ans=Math.sqrt(num11);text.setText(ans+"");}else if(str.equals("=")){s2=text.getText();double num11=Double.parseDouble(s1);double num22=Double.parseDouble(s2);double ans=0;if(s.equals("+")){ans=num11+num22;}else if(s.equals("-")){ans=num11-num22;}else if(s.equals("*")){ans=num11*num22;}else if(s.equals("/")){ans=num11/num22;}text.setText(ans+"");}}public static void main(String[] args) {ring ring=new ring();ring.setBounds(400,300,450,300);ring.show();ring.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);}}。