java计算器代码

合集下载

计算器Java编程完全代码

计算器Java编程完全代码

计算器Java编程代码1、界面截图1、程序代码import java.awt.*;import java.awt.event.*;import javax.swing.*;public class Counter implements ActionListener {// 改进小数问题private boolean append = false;JButton[] jb = new JButton[20];JTextField jtf = new JTextField(19);String[] st = { "Backs", "CE", "C", "+", " 7 ", " 8 ", " 9", "-"," 4 ", " 5 ", " 6", "*", " 1 ", " 2 ", " 3", "/"," . ", "+/-", " 0", "=", };String num1 = "0";String operator = "+";public Counter() {JFrame jf = new JFrame("计算器");// 界面设置GridLayout gl = new GridLayout(6, 1);jf.setLayout(gl);JPanel jp0 = new JPanel();jp0.add(jtf);jf.add(jp0);JPanel jp1 = new JPanel();for (int i = 0; i < 4; i++) {jb[i] = new JButton(st[i]);jp1.add(jb[i]);}jf.add(jp1);JPanel jp2 = new JPanel();for (int i = 4; i < 8; i++) {jb[i] = new JButton(st[i]);jp2.add(jb[i]);}jf.add(jp2);JPanel jp3 = new JPanel();for (int i = 8; i < 12; i++) {jb[i] = new JButton(st[i]);jp3.add(jb[i]);}jf.add(jp3);JPanel jp4 = new JPanel();for (int i = 12; i < 16; i++) { jb[i] = new JButton(st[i]);jp4.add(jb[i]);}jf.add(jp4);JPanel jp5 = new JPanel();for (int i = 16; i < 20; i++) { jb[i] = new JButton(st[i]);jp5.add(jb[i]);}jf.add(jp5);jtf.setEditable(false);// 文本框不可编辑jf.setResizable(false);// 窗口不可编辑jf.pack();// 自动调整窗口的大小// jf.setSize(240, 220);jf.setLocation(450, 300);jf.setVisible(true);jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);for (int i = 0; i < 20; i++) {// 注册监听jb[i].addActionListener(this);}}public void actionPerformed(ActionEvent ae) {String s = ae.getActionCommand();if (s.trim().matches("^\\d$")) {// 判断是输入的是否是数字if (append) {// 追加数字String ss = jtf.getText().trim();jtf.setText(ss + s.trim());} else {// 替换文本框原来的数字jtf.setText(s.trim());append = true;}} else if ("+-/*".indexOf(s.trim()) != -1) {// 判断按的是否是四则运算符num1 = jtf.getText();// 将第一次输入的数存储起来operator = s.trim();// 将输入的符号存储起来append = false;} else if ("=".equals(s.trim())) {String num2 = jtf.getText();double d1 = Double.parseDouble(num1);double d2 = Double.parseDouble(num2);if ("+".equals(operator)) {// 加法运算d1 = d1 + d2;} else if ("-".equals(operator)) {// 减法运算d1 = d1 - d2;} else if ("*".equals(operator)) {// 乘法运算d1 = d1 * d2;} else if ("/".equals(operator)) {// 除法运算d1 = d1 / d2;}jtf.setText(d1 + "");// 显示结果append = false;} else if (".".equals(s.trim())) {// 判断小数点String temp = jtf.getText();if (temp.indexOf(".") == -1) {jtf.setText(temp + ".");append = true;}} else if ("+/-".equals(s.trim())) {// 判断+/-String temp = jtf.getText();if(temp.startsWith("-")) {// 如果该数是负数则取负号后的数字jtf.setText(temp.substring(1));} else {// 如果是正数则在这个数前加上负号jtf.setText("-" + temp);}} else if ("CE".equals(s.trim()) || "C".equals(s.trim())) {// 判断复位键jtf.setText("0");append = false;} else if ("BackS".equals(s.trim())) {// 判断BackS键(删除)String temp = jtf.getText();if (temp.length() > 0) {jtf.setText(temp.substring(0, temp.length() - 1));}}}public static void main(String[] args) {new Counter();}}。

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

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

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

科学计算器代码

科学计算器代码

Calculate.java/*这是一个计算类,用于普通运算中的各种运算,如2,8,10,16进制的符合运算,复合运算其原理用后缀表达式来实现*/import java.util.*;import ng.Math;class Calculate {//两个内部类来实现数据的存储,如同数据结构中的栈class operator{ char data[];int top;operator(){data = new char [50];top = -1;}};class operator1{ double data[];int top;operator1(){data = new double [20];top = -1;}};public static double jiecheng(double number)//阶乘运算{int number1 = (int)number;double j=1;for(int i=1;i<=number1;i++)j=j*i;return j;}String trans (char exp[],char postexp[])//后缀表达式的翻译函数{int i=0,j=0;boolean m=true;//m用来监视表达式是不有非法的运算符连着输入operator op = new operator();while(exp[j]!='\0'){ switch (exp[j]){case '(':op.top++;op.data[op.top]=exp[j];j++;m= false;break;case ')':while (op.data[op.top]!='('){ postexp[i++]=op.data[op.top];op.top--;}op.top--;j++;break;case '+':case '-':if(!m)return "+或者-附近出现多个运算符在一起的现象!";while (op.top!=-1 && op.data[op.top]!='('){postexp[i++]=op.data[op.top];op.top--;}op.top++;op.data[op.top]=exp[j];j++;m=false;break;case '*':case '/':if(!m)return "*或/附近出现多个运算符在一起的现象!";while(op.top!=-1 && op.data[op.top]!='('&& op.data[op.top]!='+'&& op.data[op.top]!='-'){postexp[i++]=op.data[op.top];op.top--;}op.top++;op.data[op.top]=exp[j];j++;m = false;break;case '^':if(!m)return "^(冥运算符号)附近出现多个运算符在一起的现象!";case 's':case 'c':case 't':case 'l':case '$':case '`':op.top++;op.data[op.top]=exp[j];j++;m = false;break;case '!':op.top++;op.data[op.top]=exp[j];j++;break;case ' ':break;default:while (exp[j]>='0' && exp[j]<='9'||exp[j]=='.'){postexp[i++]=exp[j];j++;}postexp[i++]='#';m = true;}}while (op.top!=-1){postexp[i++]=op.data[op.top];op.top--;}postexp[i]='\0';if(exp[j-1]=='+'||exp[j-1]=='-'||exp[j-1]=='*'||exp[j-1]=='/'||exp[j-1]=='^') return "运算式后缀出现非正常运算符!";return "ok";}String compvalue (char postexp[],int flag)//后缀表达式运算,flag为进制{String ex = new String(postexp);StringTokenizer analy = new StringTokenizer(ex,"#+-`*/sclt!^$");operator1 st = new operator1();double d,d1,d2,a,b,c;int j=0;st.top=-1;while (postexp[j]!='\0'){switch (postexp[j]){case '+':a=st.data[st.top];st.top--;b=st.data[st.top];c=a+b;st.data[st.top]=c;break;case '-':a=st.data[st.top];st.top--;b=st.data[st.top];c=b-a;st.data[st.top]=c;break;case '*':a=st.data[st.top];st.top--;b=st.data[st.top];c=a*b;st.data[st.top]=c;break;case '/':a=st.data[st.top];st.top--;b=st.data[st.top];st.top--;if (a!=0){ c=b/a;st.top++;st.data[st.top]=c;}else{ return "输入错误,除数不能是零!请重新输入!";}break;case 's':a=st.data[st.top];c=Math.sin(Math.toRadians(a));st.data[st.top]=c;break;case 'c':a=st.data[st.top];c=Math.cos(Math.toRadians(a));st.data[st.top]=c;break;case 't':a=st.data[st.top];if(a%180 == 90||(-a)%180==90)return "tan函数值有误!";c=Math.tan(Math.toRadians(a));st.data[st.top]=c;break;case '!':a=st.data[st.top];c=jiecheng(a);st.data[st.top]=c;break;case 'l':a=st.data[st.top];if(a<=0)return "log的真数不能小于等于0";c=Math.log(a);st.data[st.top]=c;break;case '^':a=st.data[st.top];st.top--;b=st.data[st.top];c=Math.pow(b,a);st.data[st.top]=c;break;case '$':a=st.data[st.top];if(a<0)return "开方数不能小于0!";c=Math.sqrt(a);st.data[st.top]=c;break;case '`':a=st.data[st.top];c=0-a;st.data[st.top]=c;break;default:String str =analy.nextToken();//获取后缀表达式的数据if(flag == 2)d = btod(str);else if(flag == 8)d = otod(str);else if(flag == 10)d=Double.parseDouble(str);elsed = htod(str);while (postexp[j]>='0' && postexp[j]<='9'||postexp[j]=='.'){j++;}st.top++;st.data[st.top]=d;break;}j++;}return (String.valueOf(st.data[st.top]));}String check(char c[])//检查函数,用来检查运算式中的低级错误{int k=0,i=0;if(c[0]=='+'||c[0]=='-'||c[0]=='^'||c[0]=='*'||c[0]=='/')return "表达式开始位置不对";while(c[k]!='\0'){if((c[k]>=39 && c[k]<='9'&&c[k]!=',') ||c[k]=='$'||c[k]=='!'||c[k]==' '||c[k]=='c'||c[k]=='s'||c[k]=='t'||c[k]=='^'||c[k]=='l'||c[k]=='`') {}else{return "输入含有非法的字符,请重新输入正确的数学表达式!";}if(c[k]=='(')i++;else if(c[k]==')')i--;k++ ;}if(i!=0){return "输入错误,没有相匹配的括弧!请重新输入!";}return "ok";}double btod(String str)//二进制到十进制的转换{int k = str.indexOf("."),m=0;double p=0.0;if(k ==-1)k =str.length();for(int i =k-1;i>=0;i--){char c = str.charAt(i);int a =Integer.parseInt(""+c);p=p+(a*Math.pow(2, m));m++;}m=-1;for(int i =k+1;i<str.length();i++){char c = str.charAt(i);int a =Integer.parseInt(""+c);p=p+(a*Math.pow(2, m));m--;}return p;}double otod(String str)//八进制到十进制的转换{int k = str.indexOf("."),m=0;double p=0.0;if(k ==-1)k =str.length();for(int i =k-1;i>=0;i--){char c = str.charAt(i);int a =Integer.parseInt(""+c);p=p+(a*Math.pow(8, m));m++;}m=-1;for(int i =k+1;i<str.length();i++){char c = str.charAt(i);int a =Integer.parseInt(""+c);p=p+(a*Math.pow(8, m));m--;}return p;}double htod(String str)//十六进制到十进制的转换{int k = str.indexOf("."),m=0;double p=0.0;if(k ==-1)k =str.length();for(int i =k-1;i>=0;i--){char c = str.charAt(i);int a =Integer.parseInt(""+c);p=p+(a*Math.pow(16, m));m++;}m=-1;for(int i =k+1;i<str.length();i++){char c = str.charAt(i);int a =Integer.parseInt(""+c);p=p+(a*Math.pow(16, m));m--;}return p;}}Main.java//主类public class Main {public static void main(String[] args) {new WinFrame("计算器");}}MyDialog.javaimport java.awt.event.*;import java.awt.*;//帮助文档的对话框类class MyDialog extends Dialog implements ActionListener //建立对话框类{ static final int YES=1,NO=0;int message=-1; Button yes,no;TextArea area;String help;MyDialog(Frame f,String s,boolean b) //构造方法{ super(f,s,b);yes=new Button("确定"); yes.addActionListener(this);no=new Button("取消"); no.addActionListener(this);setLayout(new FlowLayout());help = "使用帮助:\n";help +="本计算器运算方式采用输入整个运算式后进行运算的方式.\n";help +="但由于作者能力有限,对有些运算符进行了重定义,现列出以下运算符:\n";help +="s代表sin,c代表cos,t代表tan,!代表阶乘,l代表log\n";help +="`代表负号,如果要用键盘输入的时候,请正确输入\n";help +="本计算器有4大主要功能:\n";help +="1.进行符合运算,可以用键盘进行输入,执行结果可以按回车获得\n";help +="2.进行2,8,10,16进制的各种运算以及相互转换,16进制没有实现a,b,c,d,e,f的输入\n";help +="3.进行大整数运算\n4.进行批量运算";area = new TextArea(help,10,50,3);//area.setEnabled(false);area.setForeground(Color.BLUE);area.setFont(new Font("宋体",Font.BOLD,16));add(area);add(yes); add(no);yes.setPreferredSize(new Dimension(100,25));no.setPreferredSize(new Dimension(100,25));setBounds(300,300,500,300);addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent e){ message=-1;setVisible(false);}});}public void actionPerformed(ActionEvent e){ if(e.getSource()==yes){ message=YES;setVisible(false);}else if(e.getSource()==no){ message=NO;setVisible(false);}}public int getMessage(){ return message;}}Mypanel.javaimport java.util.*;import java.awt.*;import javax.swing.*;class mypanel extends Panel//派生一个面板,用来实现不同面板的布局{GridLayout grid;JButton btu[];mypanel(String []btuName,int row,int col,Color c){btu = new JButton [btuName.length];grid = new GridLayout(row,col,1,1);setLayout(grid);for(int i=0;i<row;i++)for(int j=0;j<col;j++){if(i*col+j<btuName.length){btu[i*col+j] = new JButton(btuName[i*col+j]);btu[i*col+j].setForeground(c);add(btu[i*col+j]);btu[i*col+j].setPreferredSize(new Dimension(60,25));}elsebreak;}}}WinFrame.javaimport java.util.*;import java.awt.*;import java.awt.event.*;import javax.swing.*;import ng.Math;import java.math.*;class WinFrame extends Frame implements ActionListener,KeyListener,ItemListener {mypanel pane1,pane2,pane3,pane4,pane5;Label label1,label2;short j_flag=10;//进制运算的标示,初始化为十进制String strAsk="",strAnswer="";boolean b_flag = true;boolean p_flag = true;//批处理开关TextArea text1;//大整数输出专用域MenuBar menubar;Menu menu1,menu2,menu3;MenuItem item1,item2;MyDialog dialog;//帮助文档对话框CheckboxMenuItem menuitem1,menuitem2,menuitem3;String a[] = {"1","2","3",//用数组进行按钮的命名和消息内容的获取"4","5","6","7","8","9","0",".","+/-"};String a1[] = {"1","2","3","4","5","6","7","8","9","0",".","`"};String b[] ={"/","C","*","→","+","=","-","CE"};String c[] ={"sin","cos","tan","!","pow","sprt","log","pi"};String c1[] ={"s","c","t","!","^","$","l","p"};String d[] ={"( ",")"};String d1[] ={"(",")"};String e[] = {" A"," B"," C"," D"," E","F"};JTextField ask ,answer;char exp[];char postexp[];Checkbox box1,box2,box3,box4,box5;CheckboxGroup jin;String data = "0";//大整数储存数据TextArea text2,text3;int opear;CardLayout mycard;String answer1 = "";// 进制转换时的十进制答案储存Long answer2 = (long)0;//其他进制答案储存Panel pCenter;//添加一个容器装专用数据域void area()//初始化布局,只是不想在构造方法中的东西太多,看起来不方便{mycard = new CardLayout();pCenter = new Panel();pCenter.setLayout(mycard);setLayout(new FlowLayout());setBounds(60,60,450,290);menu1 = new Menu("查看");menu2 = new Menu("系统");menu3 = new Menu("帮助");menuitem1 = new CheckboxMenuItem("普通",true);menuitem2 = new CheckboxMenuItem("批处理",false);menuitem3 = new CheckboxMenuItem("大整数",false);item1 = new MenuItem("退出");item2 = new MenuItem("帮助");menuitem1.addItemListener(this);menuitem2.addItemListener(this);menuitem3.addItemListener(this);item1.addActionListener(this);item2.addActionListener(this);menubar = new MenuBar();menu1.add(menuitem1);menu1.add(menuitem2);menu1.addSeparator();//分隔符menu1.add(menuitem3);menu2.add(item1);menu3.add(item2);menuitem1.setShortcut(new MenuShortcut(KeyEvent.VK_P));menuitem2.setShortcut(new MenuShortcut(KeyEvent.VK_D)); menuitem3.setShortcut(new MenuShortcut(KeyEvent.VK_B)); item1.setShortcut(new MenuShortcut(KeyEvent.VK_Q)); item2.setShortcut(new MenuShortcut(KeyEvent.VK_F1));menubar.add(menu2);menubar.add(menu1);menubar.add(menu3);setMenuBar(menubar);dialog = new MyDialog(this,"帮助文档",true);pane1 = new mypanel(a,4,3,Color.red);pane3 = new mypanel(c,4,2,Color.black);pane2 = new mypanel(d,1,2,Color.black);pane4 = new mypanel(b,4,2,Color.BLUE);pane5 = new mypanel(e,1,6,Color.red);jin = new CheckboxGroup();box1 = new Checkbox("二进制",false,jin);box2 = new Checkbox("八进制",false,jin);box3 = new Checkbox("十进制",true,jin);box4 = new Checkbox("十六进制",false,jin);box5 = new Checkbox("大整数运算");pane3 = new mypanel(c,4,2,Color.black);for(int i=0;i<8;i++)pane3.btu[i].addActionListener(this);box1.addItemListener(this);box2.addItemListener(this);box3.addItemListener(this);box4.addItemListener(this);box5.addItemListener(this);for(int i=0;i<12;i++)pane1.btu[i].addActionListener(this);for(int i=0;i<2;i++)pane2.btu[i].addActionListener(this);for(int i=0;i<8;i++)pane4.btu[i].addActionListener(this);ask = new JTextField(38);ask.setHorizontalAlignment(JTextField.RIGHT);answer = new JTextField(38);ask.addKeyListener(this);answer.setHorizontalAlignment(JTextField.RIGHT); answer.setEditable(false);add(ask);add(answer);add(box5);add(box1);add(box2);add(box3);add(box4);text1= new TextArea("",6,10,3);text1.setForeground(Color.BLUE);pCenter.add("1",pane3);pCenter.add("2",text1);add(pCenter);add(pane1);add(pane4);add(pane2);add(pane5);label1 = new Label("请按格式输入批处理的数据,按空格输入下一个,回车输出答案。

java计算器程序代码

java计算器程序代码

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

计算器源代码

计算器源代码

今天在一个QQ群上看到一位朋友发了一个编译未通过的Java计算器源代码,遂收藏下来并将其更正。

Mark之,以供日后参考。

程序比较简单,可以说并不是很好的设计,但对于Java中swing及awt的使用,可以作为一个简单有效的例子。

运行起来如下图所示:下面,将此Java程序分享一下(详细描述见注释):/** @(#)JCalculator.java 1.00 12/29/2009** Email: light_warm@*/import java.awt.*;import java.awt.event.*;import javax.swing.*;/*** A simple calculator program.* <p>I saw this program in a QQ group, and help a friend correct it.</p> ** @author Singyuen Yip* @version 1.00 12/29/2009* @see JFrame* @see ActionListener*/public class JCalculator extends JFrame implements ActionListener { /*** Serial Version UID*/private static final long serialVersionUID = -169068472193786457L;/*** This class help close the Window.* @author Singyuen Yip**/private class WindowCloser extends WindowAdapter {public void windowClosing(WindowEvent we) {System.exit(0);}}int i;// Strings for Digit & Operator buttons.private final String[] str= { "7", "8", "9", "/", "4", "5", "6", "*", "1","2", "3", "-", ".", "0", "=", "+" };// Build buttons.JButton[] buttons = new JButton[str.length];// For cancel or reset.JButton reset = new JButton("CE");// Build the text field to show the result.JTextField display = new JTextField("0");/*** Constructor without parameters.*/public JCalculator() {super("Calculator");// Add a panel.JPanel panel1 = new JPanel(new GridLayout(4, 4));// panel1.setLayout(new GridLayout(4,4));for (i = 0; i < str.length; i++) {buttons[i] = new JButton(str[i]);panel1.add(buttons[i]);}JPanel panel2 = new JPanel(new BorderLayout());// panel2.setLayout(new BorderLayout());panel2.add("Center", display);panel2.add("East", reset);// JPanel panel3 = new Panel();getContentPane().setLayout(new BorderLayout());getContentPane().add("North", panel2);getContentPane().add("Center", panel1);// Add action listener for each digit & operator button.for (i = 0; i < str.length; i++)buttons[i].addActionListener(this);// Add listener for "reset" button.reset.addActionListener(this);// Add listener for "display" button.display.addActionListener(this);// The "close" button "X".addWindowListener(new WindowCloser());// Initialize the window size.setSize(800, 800);// Show the window.// show(); Using show() while JDK version is below 1.5.setVisible(true);// Fit the certain size.pack();}public void actionPerformed(ActionEvent e) {Object target = e.getSource();String label = e.getActionCommand();if (target == reset)handleReset();else if ("0123456789.".indexOf(label) > 0)handleNumber(label);elsehandleOperator(label);}// Is the first digit pressed?boolean isFirstDigit = true;/*** Number handling.* @param key the key of the button.*/public void handleNumber(String key) {if (isFirstDigit)display.setText(key);else if ((key.equals(".")) && (display.getText().indexOf(".") < 0))display.setText(display.getText() + ".");else if (!key.equals("."))display.setText(display.getText() + key);isFirstDigit = false;}/*** Reset the calculator.*/public void handleReset() {display.setText("0");isFirstDigit = true;operator = "=";}double number = 0.0;String operator = "=";/*** Handling the operation.* @param key pressed operator's key.*/public void handleOperator(String key) {if (operator.equals("+"))number += Double.valueOf(display.getText());else if (operator.equals("-"))number -= Double.valueOf(display.getText());else if (operator.equals("*"))number *= Double.valueOf(display.getText());else if (operator.equals("/"))number /= Double.valueOf(display.getText());else if (operator.equals("="))number = Double.valueOf(display.getText());display.setText(String.valueOf(number));operator = key;isFirstDigit = true;}public static void main(String[] args) {new JCalculator();}}。

Java实现简易计算器

Java实现简易计算器

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

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

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

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

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

java计算器源代码(仿win7)

java计算器源代码(仿win7)

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

JAVA计算器

JAVA计算器

import java.awt.*;import java.awt.event.*;import javax.swing.*;public class jisuanqi extends JFrame implements ActionListener,ItemListener{//ItemListener用于捕获带有item的组件产生的事件JTextField text;JTextField textMemory;//内存中记录boolean clickable;double memoryd;int memoryi;String copy;public jisuanqi(){super("计算器");setSize(450,230);}public void init(){clickable = true;JPanel pa1=new JPanel();pa1.setBackground(new Color(236,231,210));//设置背景色text=new JTextField("0.",38);//设置文本框长度text.setHorizontalAlignment(JTextField.RIGHT);//从右到左pa1.add("North",text);//面板添加和按钮的设置JPanel pa=new JPanel();JPanel pa2=new JPanel();JButton bt1=new JButton("Backspace");JButton bt2=new JButton("CE");JButton bt3=new JButton("c");bt3.setForeground(Color.red);bt3.setBackground(Color.gray);JButton bt4=new JButton("π");bt1.addActionListener(this);//添加监听器bt2.addActionListener(this);bt3.addActionListener(this);bt4.addActionListener(this);pa2.add(bt1);pa2.add(bt2);pa2.add(bt3);pa2.add(bt4);pa2.setLayout(new GridLayout(1,5));pa.setLayout(new BorderLayout());pa.add(pa2,"North");JPanel p1=new JPanel();p1.setLayout(new GridLayout(5,2));JButton bt5=new JButton("sin");JButton bt6=new JButton("cos");JButton bt7=new JButton("MC");JButton bt9=new JButton("MR");JButton bt11=new JButton("MS");JButton bt13=new JButton("M+");JButton bt12=new JButton("n!");JButton bt14=new JButton("%");JButton bt8=new JButton("x²");JButton bt10=new JButton("x³");bt5.addActionListener(this);//THIS的意思是指调用该类的实例对象bt6.addActionListener(this);bt7.addActionListener(this);bt8.addActionListener(this);bt9.addActionListener(this);bt10.addActionListener(this);bt11.addActionListener(this);bt12.addActionListener(this);bt13.addActionListener(this);bt14.addActionListener(this);p1.add(bt5);p1.add(bt6);p1.add(bt7);p1.add(bt8);p1.add(bt9);p1.add(bt10);p1.add(bt11);p1.add(bt12);p1.add(bt13);p1.add(bt14);pa.add(p1,"West");JPanel p = new JPanel();p.setLayout(new GridLayout(5, 5));String buttons[] = {"tan","cot","sinh","cosh","tanh","7","8","9","/","sqrt","4","5","6","*","Mod","1","2","3","-","1/x" ,"0","+/-",".","+","="};JButton btn[]=new JButton[buttons.length];for (int i = 0; i < buttons.length; i++){addButton(p, buttons[i]);pa.add(p, "Center");}pa1.add("South",pa);this.getContentPane().add(pa1);}private void addButton(Container c, String s){ JButton b = new JButton(s);c.add(b);b.addActionListener(this);}//功能的实现public void actionPerformed(ActionEvent evt){String s = evt.getActionCommand();if(s.equals("CE")||s.equals("C")){text.setText("");}////////////////////else if(s.equals("+/-"))//单击"+/-"选择输入的运算数是正数还是负数{ double x;x=Double.parseDouble(text.getText().trim());text.setText(""+(-x));}elseif (s == "sqrt") {String s1 = text.getText();if (s1.charAt(0) == '-'&& clickable == true) {text.setText("负数不能开根号");clickable = false;}elsetext.setText(Double.toString(ng.Math.sqrt(Double.parseDouble(text.getText()))));}else if(s.equals("x²"))//单击了"x²"按钮{ double x;x=Double.parseDouble(text.getText().trim());text.setText(""+(x*x));}else if(s.equals("x³"))//单击了"x³"按钮{ double x;x=Double.parseDouble(text.getText().trim());text.setText(""+(x*x*x));}else if(s.equals("n!"))//单击了"n!"按钮{ double x;double y=1.0;x=Double.parseDouble(text.getText().trim());for(int i=1;i<=x;i++){y*=i;}text.setText(""+y);}else if(s.equals("%"))//单击了"%"按钮{ double x;x=Double.parseDouble(text.getText().trim());text.setText(""+(x*0.01));}else if(s.equals("π"))//单击了"π"按钮{ double x;x=Double.parseDouble(text.getText().trim());x=x*Math.PI;text.setText(""+x);}else if(s.equals("sin"))//单击了"sin"按钮{ double x;x=Double.parseDouble(text.getText().trim()); //获取文本框中内容功能除去字符串开头和末尾的空格或其他字符x=Math.sin(x*Math.PI/180);text.setText(""+x);}else if(s.equals("cos"))//单击了"cos"按钮{ double x;x=Double.parseDouble(text.getText().trim());x=Math.cos(x*Math.PI/180);text.setText(""+x);}else if(s.equals("tan"))//单击了"tan"按钮{ double x;x=Double.parseDouble(text.getText().trim());x=Math.tan(x*Math.PI/180);text.setText(""+x);}else if(s.equals("cot"))//单击了"sin"按钮{ double x;x=Double.parseDouble(text.getText().trim()); //获取文本框中内容功能除去字符串开头和末尾的空格或其他字符x=1/(Math.tan(x*Math.PI/180));text.setText(""+x);}else if(s.equals("sinh"))//单击了"sinh"按钮{ double x;x=Double.parseDouble(text.getText().trim());x=Math.asin(x)*(180/Math.PI);text.setText(""+x);}else if(s.equals("cosh"))//单击了"cosh"按钮{ double x;x=Double.parseDouble(text.getText().trim());x=Math.acos(x)*(180/Math.PI);text.setText(""+x);}else if(s.equals("tanh"))//单击了"tanh"按钮{ double x;x=Double.parseDouble(text.getText().trim());x=Math.atan(x)*(180/Math.PI);text.setText(""+x);}else if(s.equals("1/x"))//单击了"1/X"按钮{ double x;x=Double.parseDouble(text.getText().trim());if(x==0){text.setText("除数不能为零");}else{text.setText(""+(1/x));}//按下'+/-'按钮时处理if (s== "+/-" && clickable == true) {boolean isNumber = true;String s1 = text.getText();for (int i = 0; i < s.length(); i++)if (! (s1.charAt(i) >= '0' && s1.charAt(i) <= '9' || s1.charAt(i) == '.' ||s1.charAt(i) == '-')) {isNumber = false;break;}if (isNumber == true) {//如果当前字符串首字母有'-'号,代表现在是个负数,再按下时,则将首符号去掉if (s.charAt(0) == '-') {text.setText("");for (int i = 1; i < s1.length(); i++) {char a = s1.charAt(i);text.setText(text.getText() + a);}}//如果当前字符串第一个字符不是符号,则添加一个符号在首字母处elsetext.setText('-' + s);}}//计算器有关内存操作//'MC'的操作,将内存清0elseif (s == "MC" && clickable == true) {memoryd = memoryi = 0;textMemory.setText("");}//'MS'的操作,将当前文本框内容保存入内存,显示'M'elseif (s == "MS" && clickable == true) {boolean isDot = false;textMemory.setText(" M");for (int i = 0; i < text.getText().length(); i++)if ('.' == text.getText().charAt(i)) {isDot = true;break;}//如果是double,则存入memoryd(double存储器)if (isDot == true) {memoryd = Double.parseDouble(text.getText());memoryi = 0; //保证存储器中存放最新的值}//如果是int,则存入memoryi(int存储器)else {memoryi = Integer.parseInt(text.getText());memoryd = 0; //保证存储器中存放最新的值}}//'MR'的操作,将存储器中的信息输出elseif (s == "MR" && clickable == true) {if (memoryd != 0)text.setText(Double.toString(memoryd));if (memoryi != 0)text.setText(Integer.toString(memoryi));}//'M+'的功能,将当前文本框里的数据和存储器中数据相加后,再存入存储器elseif (s == "M+" && clickable == true) {boolean isDot = false;for (int i = 0; i < text.getText().length(); i++)if ('.' == text.getText().charAt(i)) {isDot = true;break;}if (memoryi != 0) { //存储中是一个int型数if (isDot == false) //被加数是一个int型数memoryi += Integer.parseInt(text.getText());else { //被加数是一个double型数,则将int存储器中数传入double存储器与当前数相加,int存储器清零memoryd = memoryi + Double.parseDouble(text.getText());memoryi = 0;}}elsememoryd += Double.parseDouble(text.getText());}}elseif ('0' <= s.charAt(0) && s.charAt(0) <= '9' || s.equals(".")){ // text.setText("");if (start)text.setText(s);else text.setText(text.getText() + s);start = false;}else{ if (start){ if (s.equals("-")){ text.setText(s); start = false; }else op = s;}else{double x=Double.parseDouble(text.getText());calculate(x);op = s;start = true;}}}public void calculate(double n){ if (op.equals("+")) arg += n;else if (op.equals("-")) arg -= n;else if (op.equals("*")) arg *= n;else if (op.equals("/")) arg /= n;else if (op.equals("Mod")) arg %= n;else if (op.equals("=")) arg = n;text.setText("" + arg);}private double arg = 0;private String op = "=";private boolean start = true;public void itemStateChanged(ItemEvent e){}public static void main(String args[]){JFrame frame=new JFrame();jisuanqi myMenu=new jisuanqi();myMenu.init();myMenu.setVisible(true);//设置可见}}。

JAVA编写的计算器源代码

JAVA编写的计算器源代码

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

eclipse实现简单计算器代码.

eclipse实现简单计算器代码.

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

java编写的计算器设计报告

java编写的计算器设计报告

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

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

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

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

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

北邮JAVA第三次作业科学计算器(附源代码)

北邮JAVA第三次作业科学计算器(附源代码)

北邮JAVA第三次作业科学计算器(附源代码)JAVA第三次作业选题:科学计算器一、设计思路(1)布局1.数字键盘有0~9和小数点2.符号键盘有+某÷,幂,开方,lg,ln3.功能按键有清屏(AC)和删除(Del)(2)计算器流程状态转移图设定的标志位和变量有:booleannumflag=fale;//标志:是否输入数字booleanopflag=fale;//标志:是否输入运算操作符Stringt某t=null;//显示到文本框里的字符串Stringnum_t某t=\;//当前操作数的字符串形式Stringop=\;//存放输入的运算操作符num1=0;//第一个操作数num2=0;//第二个操作数privateBigDecimalbig_num1=newBigDecimal(Double.toString(0)); //解决浮点数的精度丢失问题privateBigDecimalbig_num2=newBigDecimal(Double.toString(0));1.关于操作数操作数为输入数字时会改变的数,有num1和num2。

按下运算符和控制字符,会设定当前下在键入的操作数,由opflag控制,fale表示正在操作num1,true表示正在操作num2。

初始状态下的操作数为num1。

按下AC会恢复操作数为初始状态num1。

按Delete、开方、lg、ln不会改变当前的操作数。

其中后三者只对num1有效。

其他的运算符和控制符都会使操作数为num2。

2.计算器的状态框图输入第一个数,比如53numflag=true(num1)opflag=falenum_t某t=”53”op=””t某t=”53”初始状态numflag=faleopflag=falenum_t某t=””op=””t某t=nullnum1,num2=0按下一个运算符,比如+numflag=faleopflag=truenum_t某t=””op=”+”t某t=”num1+”其中按下按=显示结果,恢复初始状态numflag=true(num1)opflag=falenum_t某t=””op=””t某t=”reult”“=”后,结果存输入第二个数,比如66入numflag=true(num2)opflag=truenum_t某t=”66”op=””t某t=”num1+66”num1,继续输入数字会在num1的结果上处理。

Java实现计算器

Java实现计算器

Java实现简易计算器,可以计算算术表达式:Java源码如下://GridFrame.java文件import java.awt.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import javax.swing.*;//计算机框架布局public class GridFrame extends JFrame{//定义面板,并设置为网格布局,4行4列,组件水平、垂直间距均为3JPanel p=new JPanel(new GridLayout(5,4,3,3));JTextArea out=new JTextArea();//定义文本框String temp="";//定义字符串数组,为按钮的显示文本赋值//注意字符元素的顺序与循环添加按钮保持一致Stringstr[]={"C","(",")","BS","7","8","9","/","4","5","6"," *","1","2","3","-","0",".","=","+"};JButton btn[]=new JButton[str.length]; //声明按钮数组public GridFrame(String s){super(s);//为窗体名称赋值setLayout(new BorderLayout());//定义窗体布局为边界布局//循环定义按钮,并添加到面板中for(int i=0;i<str.length;i++){btn[i]=new JButton(str[i]);btn[i].addActionListener(al);p.add(btn[i]);}//将文本框放置在窗体NORTH位置getContentPane().add(out,BorderLayout.NORTH);out.setRows(2);//将面板放置在窗体CENTER位置getContentPane().add(p,BorderLayout.CENTER);setVisible(true);setSize(350,250);setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);setLocationRelativeTo(null);//让窗体居中显示}//实现监听器ActionListener al=new ActionListener(){public void actionPerformed(ActionEvent e){Object currKey=e.getSource();if(currKey==btn[12]){out.setText(out.getText()+"1");}else if(currKey==btn[13]){out.setText(out.getText()+"2");}else if(currKey==btn[14]){out.setText(out.getText()+"3");}else if(currKey==btn[8]){}else if(currKey==btn[9]){ out.setText(out.getText()+"5"); }else if(currKey==btn[10]){ out.setText(out.getText()+"6"); }else if(currKey==btn[4]){ out.setText(out.getText()+"7"); }else if(currKey==btn[5]){ out.setText(out.getText()+"8"); }else if(currKey==btn[6]){ out.setText(out.getText()+"9"); }else if(currKey==btn[16]){ out.setText(out.getText()+"0"); }else if(currKey==btn[17]){ out.setText(out.getText()+"."); }else if(currKey==btn[1]){ out.setText(out.getText()+"("); }else if(currKey==btn[2]){ out.setText(out.getText()+")"); }else if(currKey==btn[7]){ out.setText(out.getText()+"/"); }else if(currKey==btn[11]){}else if(currKey==btn[15]){out.setText(out.getText()+"-");}else if(currKey==btn[19]){out.setText(out.getText()+"+");}else if(currKey==btn[18]){out.setText(out.getText()+"\n=");temp=out.getText();temp=temp.substring(0,out.getText().length()-2);;Calculator cal=new Calculator(temp);out.setText(out.getText()+String.valueOf(cal.getRes ult()));}//清除键if(currKey==btn[0]){out.setText("");}//退格键if(currKey==btn[3]){String str=out.getText();if(str.length()!=0){String str1=str.substring(0, str.length()-1);out.setText(str1);}}}};public static void main(String[]args){GridFrame gl=new GridFrame("简易计算机!");}}//ArithHelper.java文件public class ArithHelper{//默认除法运算精度private static final int DEF_DIV_SCALE=16;//这个类不能实例化private ArithHelper(){}/***提供精确的加法运算。

JAVA计算器源代码

JAVA计算器源代码

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

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

java简易计算器完整代码

java简易计算器完整代码

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

java简易计算机代码

java简易计算机代码

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

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

我们需要定义一个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编写一个简易的计算器代码

import java.awt.BorderLayout;import java.awt.Color;import java.awt.GridLayout;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.KeyEvent;import java.awt.event.KeyListener;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JPanel;import javax.swing.JTextField;/使用java 语言开发一个简易计算器/public class TestJsq extends JFrame implements ActionListener, KeyListener {private JTextField jtf;private JButton jb_bk, jb_ce, jb_c;private String xs = "";private double sum = 0;private int fh;public static void main(String[] args) {new TestJsq().creatCUI();}public void creatCUI() {JFrame jf = new JFrame();jf.setTitle("计算器");jtf = new JTextField("0.");jtf.setHorizontalAlignment(JTextField.RIGHT);jf.add(jtf, BorderLayout.NORTH);JPanel jp_main = new JPanel(new BorderLayout());jf.add(jp_main);JPanel jp1 = new JPanel(new GridLayout(1, 3, 1, 1));jb_bk = new JButton("Backspace");jb_bk.setForeground(Color.RED);jb_bk.addActionListener(this);jb_ce = new JButton("CE");jb_ce.setForeground(Color.RED);jb_ce.addActionListener(this);jb_c = new JButton("C");jb_c.setForeground(Color.RED);jb_c.addActionListener(this);jp1.add(jb_bk);jp1.add(jb_ce);jp1.add(jb_c);jp_main.add(jp1, BorderLayout.NORTH);JPanel jp2 = new JPanel(new GridLayout(4, 5, 1, 1));String str[] = { "7", "8", "9", "/", "sqrt", "4", "5", "6", "", "%","1", "2", "3", "-", "1/x", "0", "+/-", ".", "+", "=" };for (int i = 0; i < 20; i++) {JButton jb = new JButton(str[i]);jb.addActionListener(this);jb.setForeground(Color.blue);if (i == 3 || i == 8 || i == 13 || i == 18 || i == 19) { jb.setForeground(Color.RED);}jp2.add(jb);}jp_main.add(jp2, BorderLayout.CENTER);jf.setResizable(false);jf.setBounds(50, 50, 350, 350);jf.setVisible(true);}Overridepublic void actionPerformed(ActionEvent e) {String s = e.getActionCommand();if (s.equals("CE") || s.equals("C")) {xs = "";jtf.setText("0.");} else if (s.equals("Backspace")) {String str = xs.substring(0, xs.length() - 1);xs = str;jtf.setText(xs);} else if (s.equals("7") || s.equals("8") || s.equals("9") || s.equals("4") || s.equals("5") || s.equals("6")|| s.equals("1") || s.equals("2") || s.equals("3")|| s.equals("0") || s.equals(".")) {xs = xs + s;jtf.setText(xs);} else if (s.equals("+/-")) {double x = Double.parseDouble(xs);xs="" + (-x);jtf.setText(xs);} else if (s.equals("/")) {fh = 4;int point = xs.indexOf(".");if (point = -1) {String strt = xs.substring(0, point);String z = xs.substring(point + 1, xs.length());int z_num = z.length();sum = Integer.decode(strt) + (double) (Integer.decode(z))/ (10 z_num);} else {sum = Integer.decode(xs);}xs = "";jtf.setText(null);} else if (s.equals("")) {fh = 3;int point = xs.indexOf(".");if (point = -1) {String strt = xs.substring(0, point);String z = xs.substring(point + 1, xs.length());int z_num = z.length();sum = Integer.decode(strt) + (double) (Integer.decode(z))/ (10 z_num);} else {sum = Integer.decode(xs);}xs = "";jtf.setText(null);} else if (s.equals("-")) {fh = 2;int point = xs.indexOf(".");if (point = -1) {String strt = xs.substring(0, point);String z = xs.substring(point + 1, xs.length());int z_num = z.length();sum = Integer.decode(strt) + (double) (Integer.decode(z))/ (10 z_num);} else {sum = Integer.decode(xs);}xs = "";jtf.setText(null);} else if (s.equals("+")) {fh = 1;int point = xs.indexOf(".");if (point = -1) {String strt = xs.substring(0, point);String z = xs.substring(point + 1, xs.length());int z_num = z.length();sum = Integer.decode(strt) + (double) (Integer.decode(z))/ (10 z_num);} else {sum = Integer.decode(xs);}xs = "";jtf.setText(null);} else if (s.equals("sqrt")) {double x = Double.parseDouble(xs);double x1 = Math.sqrt(x);xs = x1 + "";jtf.setText(xs);} else if (s.equals("%")) {double x = Double.parseDouble(xs);x=0.01 xx;xs=x+"";jtf.setText(xs);} else if (s.equals("1/x")) {if (xs == "0") {jtf.setText("除数不能为0");} else {double x = Double.parseDouble(xs);double x1 = 1 / x;xs = x1 + "";jtf.setText(String.valueOf(xs));}} else if (s.equals("=")) {if (fh = 0) {switch (fh) {case 1:int point1 = xs.indexOf(".");if (point1 = -1) {String s1 = xs.substring(0, point1);String z1 = xs.substring(point1 + 1, xs.length());int z1_num = z1.length();xs = "";double ss1 = Integer.decode(s1)+ (double) Integer.decode(z1) / (10 z1_num);sum = sum + ss1;} else {sum = sum + Integer.decode(xs);xs = "";}fh = 0;break;case 2:int point2 = xs.indexOf(".");if (point2 = -1) {String s2 = xs.substring(0, point2);String z2 = xs.substring(point2 + 1, xs.length());int z2_num = z2.length();xs = "";double ss2 = Integer.decode(s2)+ (double) Integer.decode(z2) / (10 z2_num);sum = sum - ss2;} else {sum = sum - Integer.decode(xs);xs = "";}fh = 0;break;case 3:int point3 = xs.indexOf(".");if (point3 = -1) {String s3 = xs.substring(0, point3);String z3 = xs.substring(point3 + 1, xs.length());int z1_num = z3.length();xs = "";double s4 = Integer.decode(s3)+ (double) Integer.decode(z3) / (10 z1_num);sum = sum s4;} else {sum = sum Integer.decode(xs);xs = "";}fh = 0;break;case 4:int point4 = xs.indexOf(".");if (point4 = -1) {String s4 = xs.substring(0, point4);String z4 = xs.substring(point4 + 1, xs.length());int z4_num = z4.length();xs = "";double s5 = Integer.decode(s4)+ (double) Integer.decode(z4) / (10 z4_num);sum = sum / s5;} else {sum = sum / Integer.decode(xs);xs = "";}fh = 0;break;default:break;}xs = String.valueOf(sum);jtf.setText(xs);fh = 0;} else {jtf.setText(null);}}}Overridepublic void keyPressed(KeyEvent e) {// TODO Auto-generated method stub}Overridepublic void keyReleased(KeyEvent e) { // TODO Auto-generated method stub }Overridepublic void keyTyped(KeyEvent e) { // TODO Auto-generated method stub }}。

java 计算器

java 计算器

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

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

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

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

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

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

java计算器代码import java.awt.*;import java.awt.event.*;class leiyi extends Frame {static double con1=0;static int jihao=0;static int xiao=0;static int jishu=10;private Button button1=new Button("7"); private Button button2=new Button("8"); private Button button3=new Button("9"); private Button button4=new Button("+"); private Button button5=new Button("4"); private Button button6=new Button("5"); private Button button7=new Button("6"); private Button button8=new Button("-"); private Button button9=new Button("1"); private Button button10=new Button("2"); private Button button11=new Button("3"); private Button button12=new Button("="); private Button button13=new Button("*"); private Button button14=new Button("/"); private Button button15=new Button("0");private Button button16=new Button("CE"); private Button button17=new Button("."); private Button button18=new Button("根号"); private Button button19=new Button("平方"); private TextArea textarea1=new TextArea("0"); public leiyi(){super("小小计算器");//GridLayout card1=new GridLayout(5,4,5,5); //setLayout(card1);setLayout(null);textarea1.setBounds(10,40,270,50);button1.setBounds(15,90,50,50);button2.setBounds(85,90,50,50);button3.setBounds(155,90,50,50);button4.setBounds(225,90,50,50);button5.setBounds(15,145,50,50);button6.setBounds(85,145,50,50);button7.setBounds(155,145,50,50);button8.setBounds(225,145,50,50);button9.setBounds(15,200,50,50);button10.setBounds(85,200,50,50);button11.setBounds(155,200,50,50);button12.setBounds(225,200,50,105);button13.setBounds(15,255,50,50); button14.setBounds(85,255,50,50); button15.setBounds(155,255,50,50); button16.setBounds(225,310,50,50); button16.setForeground(Color.red); button16.setBackground(Color.pink); button17.setBounds(15,310,50,50); button18.setBounds(85,310,50,50); button19.setBounds(155,310,50,50); add(button1);add(button2);add(button3);add(button4);add(button5);add(button6);add(button7);add(button8);add(button9);add(button10);add(button11);add(button12);add(button13);add(button14);add(button15);add(button16);add(textarea1);add(button17);add(button18);add(button19);button1.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {if(xiao==0){String tmp1 =textarea1.getText();double a2=Double.parseDouble(tmp1);double a3=a2*10+7.0;String tmp4 =String.valueOf(a3);textarea1.setText(tmp4);}if(xiao==1){String tmp1 =textarea1.getText();double a2=Double.parseDouble(tmp1);double a3=a2+(7.0/jishu);jishu=jishu*10;String tmp4 =String.valueOf(a3);textarea1.setText(tmp4);}}});button2.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {if(xiao==0){String tmp1 =textarea1.getText();double a2=Double.parseDouble(tmp1);double a3=a2*10+8.0;String tmp4 =String.valueOf(a3);textarea1.setText(tmp4);}if(xiao==1){String tmp1 =textarea1.getText();double a2=Double.parseDouble(tmp1);double a3=a2+(8.0/jishu);jishu=jishu*10;String tmp4 =String.valueOf(a3);textarea1.setText(tmp4);}}});button3.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e) {if(xiao==0){String tmp1 =textarea1.getText();double a2=Double.parseDouble(tmp1);double a3=a2*10+9.0;String tmp4 =String.valueOf(a3);textarea1.setText(tmp4);}if(xiao==1){String tmp1 =textarea1.getText();double a2=Double.parseDouble(tmp1);double a3=a2+(9.0/jishu);jishu=jishu*10;String tmp4 =String.valueOf(a3);textarea1.setText(tmp4);}}});button5.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {if(xiao==0){String tmp1 =textarea1.getText();double a2=Double.parseDouble(tmp1);double a3=a2*10+4.0;String tmp4 =String.valueOf(a3);textarea1.setText(tmp4);}if(xiao==1){String tmp1 =textarea1.getText();double a2=Double.parseDouble(tmp1);double a3=a2+(4.0/jishu);jishu=jishu*10;String tmp4 =String.valueOf(a3);textarea1.setText(tmp4);}}});button6.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {if(xiao==0){String tmp1 =textarea1.getText();double a2=Double.parseDouble(tmp1);double a3=a2*10+5.0;String tmp4 =String.valueOf(a3);textarea1.setText(tmp4);}if(xiao==1){String tmp1 =textarea1.getText();double a2=Double.parseDouble(tmp1);double a3=a2+(5.0/jishu);jishu=jishu*10;String tmp4 =String.valueOf(a3);textarea1.setText(tmp4);}}});button7.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {if(xiao==0){String tmp1 =textarea1.getText();double a2=Double.parseDouble(tmp1);double a3=a2*10+6.0;String tmp4 =String.valueOf(a3);textarea1.setText(tmp4);}if(xiao==1){String tmp1 =textarea1.getText();double a2=Double.parseDouble(tmp1);double a3=a2+(6.0/jishu);jishu=jishu*10;String tmp4 =String.valueOf(a3);textarea1.setText(tmp4);}}});button9.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {if(xiao==0){String tmp1 =textarea1.getText();double a2=Double.parseDouble(tmp1);double a3=a2*10+1.0;String tmp4 =String.valueOf(a3);textarea1.setText(tmp4);}if(xiao==1){String tmp1 =textarea1.getText();double a2=Double.parseDouble(tmp1);double a3=a2+(1.0/jishu);jishu=jishu*10;String tmp4 =String.valueOf(a3);textarea1.setText(tmp4);}}});button10.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {if(xiao==0){String tmp1 =textarea1.getText();double a2=Double.parseDouble(tmp1);double a3=a2*10+2.0;String tmp4 =String.valueOf(a3);textarea1.setText(tmp4);}if(xiao==1){String tmp1 =textarea1.getText();double a2=Double.parseDouble(tmp1);double a3=a2+(2.0/jishu);jishu=jishu*10;String tmp4 =String.valueOf(a3);textarea1.setText(tmp4);}}});button11.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {if(xiao==0){String tmp1 =textarea1.getText();double a2=Double.parseDouble(tmp1);double a3=a2*10+3.0;String tmp4 =String.valueOf(a3);textarea1.setText(tmp4);}if(xiao==1){String tmp1 =textarea1.getText();double a2=Double.parseDouble(tmp1);double a3=a2+(3.0/jishu);jishu=jishu*10;String tmp4 =String.valueOf(a3);textarea1.setText(tmp4);}}});button15.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {if(xiao==0){String tmp1 =textarea1.getText();double a2=Double.parseDouble(tmp1);double a3=a2*10+0.0;String tmp4 =String.valueOf(a3);textarea1.setText(tmp4);}if(xiao==1){String tmp1 =textarea1.getText();double a2=Double.parseDouble(tmp1);double a3=a2+(0.0/jishu);jishu=jishu*10;String tmp4 =String.valueOf(a3);textarea1.setText(tmp4);}}});button8.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e) {String tmp1 =textarea1.getText();double a2=Double.parseDouble(tmp1);textarea1.setText("0");con1=a2;jihao=2;jishu=10;xiao=0;}});button13.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {String tmp1 =textarea1.getText();double a2=Double.parseDouble(tmp1);textarea1.setText("0");con1=a2;jihao=3;jishu=10;xiao=0;}});button14.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {String tmp1 =textarea1.getText();double a2=Double.parseDouble(tmp1);textarea1.setText("0");con1=a2;jihao=4;jishu=10;xiao=0;}});button18.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {String tmp1 =textarea1.getText();double a2=Double.parseDouble(tmp1);double ba=Math.sqrt(a2);String tmp=String.valueOf(ba);textarea1.setText(tmp);}});button19.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {String tmp1 =textarea1.getText();double a2=Double.parseDouble(tmp1);double ba=a2*a2;String tmp=String.valueOf(ba);textarea1.setText(tmp);}});button4.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {String tmp1 =textarea1.getText();con1=Double.parseDouble(tmp1);textarea1.setText("0");jihao=1;jishu=10;xiao=0;}});button17.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {xiao=1;}});button12.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {String tmp1 =textarea1.getText();double a1=Double.parseDouble(tmp1);double a2=con1;double a3=0;if(jihao==4&&a1==0){textarea1.setText("分母不能为0");}if(jihao==1){a3=a1+a2;String tmp4 =String.valueOf(a3);textarea1.setText(tmp4);}if(jihao==2){a3=a2-a1;String tmp4 =String.valueOf(a3);textarea1.setText(tmp4);}if(jihao==3){a3=a1*a2;String tmp4 =String.valueOf(a3);textarea1.setText(tmp4);}if (jihao==4&&a1!=0){a3=a2/a1;String tmp4 =String.valueOf(a3);textarea1.setText(tmp4);}}});button16.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {textarea1.setText("0");con1=0;jihao=0;xiao=0;jishu=10;}});setBounds(50,50,300,400);setVisible(true);}}public class jisuanqi {public static void main(String[] args) { new leiyi();}}。

相关文档
最新文档