Java科学计算器程序代码

合集下载

java科学计算器源代码

java科学计算器源代码

import java.awt.*;import javax.swing.*;import java.awt.event.*;class Counter extends WindowAdapter{static JFrame f=new JFrame("计算器"); static JTextField text1=new JTextField("0."); static String source="";static String cal="";static String object="";static boolean flag=false;static boolean flag1=true;static boolean flag2=false;public void init(){try{Container c=f.getContentPane();JPanel pan1=new JPanel();JButton b1=new JButton("1");JButton b2=new JButton("2");JButton b3=new JButton("3");JButton b4=new JButton("4");JButton b5=new JButton("5");JButton b6=new JButton("6");JButton b7=new JButton("7");JButton b8=new JButton("8");JButton b9=new JButton("9");JButton b0=new JButton("0");JButton b11=new JButton("+");JButton b12=new JButton("-");JButton b13=new JButton("*");JButton b14=new JButton("/");JButton b15=new JButton(".");JButton b16=new JButton("=");JButton bclar=new JButton("清零");text1.setHorizontalAlignment(JTextField.RIGHT);c.add(text1,"North");c.add(pan1);A aa=new A();Result re=new Result();Opertion op=new Opertion();Clar cl=new Clar();b1.addActionListener(aa);b2.addActionListener(aa);b3.addActionListener(aa);b4.addActionListener(aa);b5.addActionListener(aa);b6.addActionListener(aa);b7.addActionListener(aa);b8.addActionListener(aa);b9.addActionListener(aa);b0.addActionListener(aa);b11.addActionListener(op);b12.addActionListener(op);b13.addActionListener(op);b14.addActionListener(op);b16.addActionListener(re);b15.addActionListener(aa);bclar.addActionListener(cl);pan1.add(b1);pan1.add(b2);pan1.add(b3);pan1.add(b11);pan1.add(b4);pan1.add(b5);pan1.add(b6);pan1.add(b12);pan1.add(b7);pan1.add(b8);pan1.add(b9);pan1.add(b13);pan1.add(b0);pan1.add(b15);pan1.add(b16);pan1.add(b14);pan1.add(bclar);f.setSize(200,220);f.setVisible(true);}catch(Exception e){System.out.println(e.getMessage());}}class A implements ActionListener{public void actionPerformed(ActionEvent e) {String a=text1.getText();String s=e.getActionCommand();if(a.equals("0.")||a.equals("+")||a.equals("-")||a.equals("*")||a.equals("/")) text1.setText(s);else {if(flag2){text1.setText(s);flag2=false;}elsetext1.setText(a+s);}}}class Opertion implements ActionListener{public void actionPerformed(ActionEvent e){cal=e.getActionCommand();if(flag1==true)source=text1.getText();text1.setText(cal);flag1=false;flag=true;}}class Result implements ActionListener{public void actionPerformed(ActionEvent e){double num1;num1=Double.parseDouble(source); object=text1.getText();double num2;num2=Double.parseDouble(object); double result=0;if(cal.equals("+"))result=num1+num2;if(cal.equals("-"))result=num1-num2;if(cal.equals("*"))result=num1*num2;if(cal.equals("/"))if(num2==0)text1.setText("除数不能为0");elseresult=num1/num2;String s1=Double.toString(result);text1.setText(s1);flag1=true;flag2=true;}}class Clar implements ActionListener{public void actionPerformed(ActionEvent e) {text1.setText("0.");}}public static void main(String[] args){Counter count=new Counter();count.init();}public void windowClosing(WindowEvent e){ System.exit(1);}public void windowOpened(WindowEvent e){} public void windowIconified(WindowEvent e){} public void windowDeiconified(WindowEvent e){} public void windowClosed(WindowEvent e){} public void windowActivated(WindowEvent e){} public void windowDeactivated(WindowEvent e){} }。

科学计算器程序Java代码

科学计算器程序Java代码

科学计算器程序Java代码MC:清除独立内存里的数字MR:读出独立内存数字MS:将显示数字保存到独立内存,并取代内存中原有数字M+:将显示数字向独立内存累加(独立内存是一个临时寄放数字的存储器,方便计算)CE:纠错键(CLEAR ERROR).输入数字有错,按它可以重新输入C:表示清零,将计算器恢复到开机状态功能举例:源程序如下:import java.awt.BorderLayout;import javax.swing.JRadioButtonMenuItem; import javax.swing.JTextField;public class Calucator extends JFrame { private JTextField tf;private JPanel panel1, panel2, panel3, panel4;private JMenuBar myBar;private JMenu menu1, menu2, menu3;private JMenuItem editItem1, editItem2, help1, help2, help3;private JRadioButtonMenuItem seeItem1, seeItem2;//单选框private JCheckBoxMenuItem seeItem3;//复选框private ButtonGroup bgb;private String back;private boolean IfResult = true, flag = false;private String oper = "=";private double result = 0;private Num numActionListener;private DecimalFormat df;public Calucator(){super("科学计算器");//设置标题栏df= new DecimalFormat("#.####");//保留四位小数this.setLayout(new BorderLayout(10, 5));panel1 = new JPanel(new GridLayout(1, 3, 10, 10));panel2 = new JPanel(new GridLayout(5, 6, 5, 5));//5行6列panel3 = new JPanel(new GridLayout(5, 1, 5, 5));panel4= new JPanel(new BorderLayout(5, 5));/***菜单栏*/myBar = new JMenuBar();menu1 = new JMenu("编辑(E)");menu2 = new JMenu("查看(V)");menu3 = new JMenu("帮助(H)");menu1.setFont(new Font("宋体", Font.PLAIN, 12));menu2.setFont(new Font("宋体", Font.PLAIN, 12));menu3.setFont(new Font("宋体", Font.PLAIN, 12));/***编辑栏*/editItem1= new JMenuItem("复制(C) Ctrl+C");editItem2= new JMenuItem("粘贴(P) Ctrl+V");editItem1.setFont(new Font("宋体",Font.PLAIN,12));editItem2.setFont(new Font("宋体",Font.PLAIN,12));/***查看栏*/seeItem1= new JRadioButtonMenuItem("科学型(T)");seeItem2= new JRadioButtonMenuItem("标准型(S)");seeItem3= new JCheckBoxMenuItem("数字分组(I)");seeItem1.setFont(new Font("宋体",Font.PLAIN,12));seeItem2.setFont(new Font("宋体",Font.PLAIN,12));seeItem3.setFont(new Font("宋体",Font.PLAIN,12));/***帮助栏*/help1 = new JMenuItem("帮助主题(H)");help2= new JMenuItem("关于计算器(A)");help1.setFont(new Font("宋体",Font.PLAIN,12));help2.setFont(new Font("宋体",Font.PLAIN,12));bgb = new ButtonGroup();//选项组menu1.add(editItem1);menu1.add(editItem2);menu2.add(seeItem1);menu2.add(seeItem2);menu2.addSeparator();//添加一条分割线menu2.add(seeItem3);menu3.add(help1);menu3.addSeparator();//添加一条分割线menu3.add(help2);myBar.add(menu1);myBar.add(menu2);myBar.add(menu3);this.setJMenuBar(myBar);numActionListener= new Num();//实现数字监听/***文本域,即为计算器的屏幕显示区域*/tf = new JTextField();tf.setEditable(false);//文本区域不可编辑tf.setBackground(Color.white);//文本区域的背景色tf.setHorizontalAlignment(JTextField.RIGH T);//文字右对齐tf.setText("0");tf.setBorder(BorderFactory.createLoweredB evelBorder());init();//对计算器进行初始化}/***初始化操作*添加按钮*/private void init(){addButton(panel1, "Backspace", newClear(), Color.red);addButton(panel1, "CE", new Clear(), Color.red);addButton(panel1, "C", new Clear(), Color.red);addButton(panel2, "1/x", new Signs(), Color.magenta);addButton(panel2, "log", new Signs(), Color.magenta);addButton(panel2, "7", numActionListener, Color.blue);addButton(panel2, "8", numActionListener, Color.blue);addButton(panel2, "9", numActionListener, Color.blue);addButton(panel2, "÷", new Signs(), Color.red);addButton(panel2, "n!", new Signs(), Color.magenta);addButton(panel2, "sqrt", new Signs(), Color.magenta);addButton(panel2, "4", numActionListener, Color.blue);addButton(panel2, "5", numActionListener, Color.blue);addButton(panel2, "6", numActionListener, Color.blue);addButton(panel2, "×", new Signs(), Color.red);addButton(panel2, "sin", new Signs(), Color.magenta);addButton(panel2, "x^2", new Signs(), Color.magenta);addButton(panel2, "1", numActionListener, Color.blue);addButton(panel2, "2", numActionListener, Color.blue);addButton(panel2, "3", numActionListener, Color.blue);addButton(panel2, "-", new Signs(), Color.red);addButton(panel2, "cos", new Signs(), Color.magenta);addButton(panel2, "x^3", new Signs(), Color.magenta);addButton(panel2, "0", numActionListener, Color.blue);addButton(panel2, "-/+", new Clear(), Color.blue);addButton(panel2, ".", new Dot(), Color.blue);addButton(panel2, "+", new Signs(), Color.red);addButton(panel2, "tan", new Signs(), Color.magenta);addButton(panel2, "%", new Signs(), Color.magenta);addButton(panel2, "π", numActionListener, Color.orange);addButton(panel2, "e", numActionListener, Color.orange);addButton(panel2, "′″", new Signs(), Color.orange);addButton(panel2, "=", new Signs(), Color.red);JButton btns = new JButton("计算器");btns.setBorder(BorderFactory.createLowere dBevelBorder());btns.setEnabled(false);//按钮不可操作btns.setPreferredSize(new Dimension(20, 20));panel3.add(btns);//加入按钮addButton(panel3, "MC", null, Color.red);addButton(panel3, "MR", null, Color.red);addButton(panel3, "MS", null, Color.red);addButton(panel3, "M+", null, Color.red);panel4.add(panel1,BorderLayout.NORTH);panel4.add(panel2,BorderLayout.CENTER);this.add(tf, BorderLayout.NORTH);this.add(panel3, BorderLayout.WEST);this.add(panel4);pack();this.setResizable(false);//窗口不可改变大小this.setLocation(300, 200);this.setDefaultCloseOperation(JFrame.EXIT _ON_CLOSE);}/***统一设置按钮的的使用方式*@param panel*@param name*@param action*@param color*/private void addButton(JPanel panel, String name, ActionListener action, Color color){JButton bt = new JButton(name);panel.add(bt);//在面板上增加按钮bt.setForeground(color);//设置前景(字体)颜色bt.addActionListener(action);//增加监听事件}/***计算器的基础操作(+-×÷)*@param x*/private void getResult (double x){if(oper == "+"){result += x;}else if(oper == "-"){result -= x;}else if(oper == "×"){result *= x;}else if(oper == "÷"){result /= x;}else if(oper == "="){result = x;}tf.setText(df.format(result));}/***运算符号的事件监听*/class Signs implements ActionListener{ public void actionPerformed(ActionEvent e) {/** 用ActionEvent对象的getActionCommand()方法* 取得与引发事件对象相关的字符串*/String str = e.getActionCommand();/* sqrt求平方根*/if(str.equals("sqrt")){double i = Double.parseDouble(tf.getText());if(i>=0){/** String.valueOf() 转换为字符串* df.format() 按要求保留四位小数* Math.sqrt() 求算数平方根*/tf.setText(String.valueOf(df.format(Math.sq rt(i))));}else{tf.setText("负数不能开平方根");}}/* log求常用对数*/else if(str.equals("log")){double i = Double.parseDouble(tf.getText());if(i>0){tf.setText(String.valueOf(df.format(Math.lo g(i))));}else{tf.setText("负数不能求对数");}}/* %求百分比*/else if(str.equals("%")){tf.setText(df.format(Double.parseDouble(tf. getText()) / 100));}/* 1/x求倒数*/else if(str.equals("1/x")){if(Double.parseDouble(tf.getText()) == 0){tf.setText("除数不能为零");}else{tf.setText(df.format(1 / Double.parseDouble(tf.getText())));}}/* sin求正弦函数*/else if(str.equals("sin")){double i = Double.parseDouble(tf.getText());tf.setText(String.valueOf(df.format(Math.si n(i))));}/* cos求余弦函数*/else if(str.equals("cos")){double i = Double.parseDouble(tf.getText());tf.setText(String.valueOf(df.format(Math.co s(i))));}/* tan求正切函数*/else if(str.equals("tan")){double i = Double.parseDouble(tf.getText());tf.setText(String.valueOf(df.format(Math.ta n(i))));}/* n!求阶乘*/else if(str.equals("n!")){double i = Double.parseDouble(tf.getText());if((i%2==0)||(i%2==1))//判断为整数放进行阶乘操作{int j = (int)i;//强制类型转换int result=1;for(int k=1;k<=j;k++)result *= k;tf.setText(String.valueOf(result));}else{tf.setText("无法进行阶乘");}}/* x^2求平方*/else if(str.equals("x^2")){double i = Double.parseDouble(tf.getText());tf.setText(String.valueOf(df.format(i*i)));}/* x^3求立方*/else if(str.equals("x^3")){double i =Double.parseDouble(tf.getText());tf.setText(String.valueOf(df.format(i*i*i)));}/* ′″角度转换*//***将角度值转换成弧度值,方便三角函数的计算*/else if(str.equals("′″")){double i = Double.parseDouble(tf.getText());tf.setText(String.valueOf(i/180*Math.PI));}else{if(flag){IfResult = false;}if(IfResult){oper = str;}else{getResult(Double.parseDouble(tf.getText()) );oper = str;IfResult = true;}}}}/***清除按钮的事件监听*/class Clear implements ActionListener{ public void actionPerformed(ActionEvent e) {/** 用ActionEvent对象的getActionCommand()方法* 取得与引发事件对象相关的字符串*/String str = e.getActionCommand();if(str == "C"){tf.setText("0");IfResult = true;result = 0;}else if(str == "-/+"){double i = 0 - Double.parseDouble(tf.getText().trim());tf.setText(df.format(i));}else if(str == "Backspace"){if(Double.parseDouble(tf.getText()) > 0){if(tf.getText().length() > 1){tf.setText(tf.getText().substring(0,tf.getText().length() - 1));//使用退格删除最后一位字符}else{tf.setText("0");IfResult = true;}}else{if(tf.getText().length() > 2){tf.setText(tf.getText().substring(0,tf.getText().length() - 1));}else{tf.setText("0");IfResult = true;}}}else if(str == "CE"){tf.setText("0");IfResult = true;}}}/***数字输入的事件监听*/class Num implements ActionListener{ public void actionPerformed(ActionEvent e) {String str = e.getActionCommand(); if(IfResult){tf.setText("");IfResult = false;}if(str=="π"){tf.setText(String.valueOf(Math.PI)); }else if(str=="e"){tf.setText(String.valueOf(Math.E)); }else{tf.setText(tf.getText().trim() + str);if(tf.getText().equals("0")){tf.setText("0");IfResult = true;flag = true;}}}}/***小数点的事件监听*/class Dot implements ActionListener{ public void actionPerformed(ActionEvent e) {IfResult = false;if(tf.getText().trim().indexOf(".") == -1){tf.setText(tf.getText() + ".");}}}/***main方法*/public static void main(String[] args) { new Calucator().setVisible(true);}}。

计算器JAVA源代码

计算器JAVA源代码

import java.awt.*;import javax.swing.*;import java.awt.Event.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;public class Calculation extends JFrame implements ActionListener {private JTextField result;JTextField fm;Double dm = 0d;public Calculation(){super("计算器");result = new JTextField("0",30);result.setBackground(Color.white);result.setHorizontalAlignment(JTextField.RIGHT);result.setEditable(false);JPanel resultpanel = new JPanel();resultpanel.add(result);fm = new JTextField(2);JButton b1= new JButton("Backspace");JButton b2= new JButton("CE");JButton b3= new JButton("C");JPanel ControalPanel = new JPanel();ControalPanel.setLayout(new GridLayout(1,4,2,2));ControalPanel.add(fm);ControalPanel.add(b1);ControalPanel.add(b2);ControalPanel.add(b3);b1.addActionListener(this);b2.addActionListener(this);b3.addActionListener(this);String dckey [] = {"MC","0","1","2","3","4","5","6","7","8","9","/","sqrt","MR","*","%","MS","-","1/x","M+","+/-" ,".","+","="};JPanel dckeypanel =new JPanel();dckeypanel.setLayout(new GridLayout(4,6,2,2));for(int i=0;i<24;i++){JButton b = new JButton(dckey[i]);dckeypanel.add(b);b.addActionListener(this);}Container ct = this.getContentPane();ct.setLayout(new BorderLayout());ct.add(resultpanel,BorderLayout.NORTH);ct.add(ControalPanel,BorderLayout.CENTER);ct.add(dckeypanel,BorderLayout.SOUTH);pack();setVisible(true);setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);}private boolean newDigital = true;private int optionvalue;private String operation = "";private Double d,d1,d2;public void actionPerformed(ActionEvent e){String s = (e.getActionCommand());String str = result.getText();if(s.equals("Backspace")){String s1 = result.getText();result.setText(s1.substring(0,s1.length()-1));}if(s.equals("CE")){result.setText("0");newDigital = true;}if(s.equals("C")){result.setText("0");optionvalue = 0;newDigital = true;}if(s.equals("0")||s.equals("1")||s.equals("2")||s.equals("3")||s.equals("4")||s.equals("5")||s.equal s("6")||s.equals("7")||s.equals("8")||s.equals("9")){if(!newDigital){result.setText(str+s);}else{result.setText(s);newDigital = false;}return;}if(s.equals(".")){if(result.getText().trim().startsWith("0")){result.setText("0.");newDigital = false;}else{result.setText(str+".");}return;}if(s.equals("+/-")){d = Double.parseDouble(str.trim());result.setText(String.valueOf((-d)));return;}if(s.equals("+")){d1 = Double.parseDouble(result.getText());optionvalue = 1;result.setText("");}if(s.equals("-")){d1 = Double.parseDouble(result.getText());optionvalue = 2;result.setText("");}if(s.equals("*")){d1 = Double.parseDouble(result.getText());optionvalue = 3;result.setText("");}if(s.equals("/")){d1 = Double.parseDouble(result.getText());optionvalue = 4;result.setText("");}if(s.equals("=")){d2 = Double.parseDouble(result.getText());switch(optionvalue){case 1:result.setText(String.valueOf(d1+d2));break;case 2:result.setText(String.valueOf(d1-d2));break;case 3:result.setText(String.valueOf(d1*d2));break;case 4:if(d2!=0){result.setText(String.valueOf(d1/d2));}else{result.setText("除数不能为零");return;}break;}operation = "";}if(s.equals("sqrt")){d = Double.parseDouble(result.getText().trim());if(d>=0){result.setText(String.valueOf((Math.sqrt(d))));}else{result.setText("除数不能为零");}}if(s.equals("1/x")){d = Double.parseDouble(result.getText().trim());if(str.equals("0")){result.setText("除数不能为零");}else{result.setText(String.valueOf((1/d)));}}if(s.equals("%")){result.setText(String.valueOf((Double.parseDouble(str)/100))); }if(s.equals("MC")){fm.setText("");dm=0d;newDigital = true;}if(s.equals("MR")){if(fm.getText().trim()!=""){result.setText(""+dm);}}if(s.equals("MS")){dm = Double.parseDouble(result.getText().trim());fm.setText("M");}if(s.equals("M+")){dm = dm+Double.parseDouble(result.getText().trim());}}public static void main (String [] args){ new Calculation();}}。

计算器完整代码(java)

计算器完整代码(java)

1. Calculator 类import java.applet.*;import java.awt.*;import java.awt.event.*;import ng.*;import java.applet.Applet;import javax.swing.*;import javax.swing.border.*;public class Calculator extends JApplet implements ActionListener {private final String[] KEYS={"7","8","9","/","sqrt", "4","5","6","*","%","1","2","3","-","1/x","0","+/-",".","+","="};private final String[] COMMAND={"Backspace","CE","C"};private final String[] M={" ","MC","MR","MS","M+"};private JButton keys[]=new JButton[KEYS.length];private JButton commands[]=new JButton[COMMAND.length];private JButton m[]=new JButton[M.length];private JTextField display =new JTextField("0");// public JTextField setHorizontalAlignment(int alignment);// private JTextFielddisplay.setHorizontalAlignment(JTextField.RIGHT)=new JTextField("0"); private void setup(){display.setHorizontalAlignment(JTextField.RIGHT);JPanel calckeys=new JPanel();JPanel command=new JPanel();JPanel calms=new JPanel();calckeys.setLayout(new GridLayout(4,5,3,3));command.setLayout(new GridLayout(1,3,3,3));calms.setLayout(new GridLayout(5,1,3,3));for(int i=0;i<KEYS.length;i++){keys[i]=new JButton(KEYS[i]);calckeys.add(keys[i]);keys[i].setForeground(Color.blue);}keys[3].setForeground(Color.red);keys[4].setForeground(Color.red);keys[8].setForeground(Color.red);keys[9].setForeground(Color.red);keys[13].setForeground(Color.red);keys[14].setForeground(Color.red);keys[18].setForeground(Color.red);keys[19].setForeground(Color.red);for(int i=0;i<COMMAND.length;i++){commands[i]=new JButton(COMMAND[i]);command.add(commands[i]);commands[i].setForeground(Color.red);}for(int i=0;i<M.length;i++){m[i]=new JButton(M[i]);calms.add(m[i]);m[i].setForeground(Color.red);}JPanel panel1=new JPanel();panel1.setLayout(new BorderLayout(3,3));panel1.add("North",command);panel1.add("Center",calckeys);JPanel top=new JPanel();top.setLayout(new BorderLayout());display.setBackground(Color.WHITE);top.add("Center",display);getContentPane().setLayout(new BorderLayout(3,5)); getContentPane().add("North",top);getContentPane().add("Center",panel1); getContentPane().add("West",calms);}public void init(){setup();for(int i=0;i<KEYS.length;i++){keys[i].addActionListener(this);}for(int i=0;i<COMMAND.length;i++){commands[i].addActionListener(this);}for(int i=0;i<M.length;i++){m[i].addActionListener(this);}display.setEditable(false);}public void actionPerformed(ActionEvent e){String label=e.getActionCommand();// double zero=e.getActionCommand();if(label=="C")handleC();else if(label=="Backspace")handleBackspace();else if(label=="CE")display.setText("0");else if (label=="1/x")daoShu();else if(label=="sqrt"){display.setText(Math.sqrt(getNumberFromDisplay())+"");}else if("0123456789.".indexOf(label)>=0){handleNumber(label);// handlezero(zero);}elsehandleOperator(label);}private boolean firstDigit=true;private void handleNumber(String key){if(firstDigit){ if(key.equals("0"))display.setText(key);else if(key.equals(".")){display.setText("0.");firstDigit=false;}else if(!key.equals("0")&&!key.equals(".")){display.setText(key);firstDigit=false;}}else if((key.equals("."))&&(display.getText().indexOf(".")<0)) display.setText(display.getText()+".");else if(!key.equals(".")&&display.getText().length()<=32) display.setText(display.getText()+key);}private double number=0;private String operator="=";private void handleOperator(String key){if(operator.equals("/")){if(getNumberFromDisplay()==0){display.setText("除数不能为零");}else{number/=getNumberFromDisplay();}long t1;double t2;t1=(long)number;t2=number-t1;if(t2==0){display.setText(String.valueOf(t1));}else{display.setText(String.valueOf(number));}}else if(operator.equals("+"))number+=getNumberFromDisplay();else if(operator.equals("-"))number-=getNumberFromDisplay();else if(operator.equals("*"))number*=getNumberFromDisplay();else if(operator.equals("%"))number=number/100;else if(operator.equals("+/-"))number=number*(-1);else if(operator.equals("="))number=getNumberFromDisplay();long t1;double t2;t1=(long)number;t2=number-t1;if(t2==0)display.setText(String.valueOf(t1));elsedisplay.setText(String.valueOf(number));operator=key;firstDigit=true;}private double getNumberFromDisplay(){return Double.valueOf(display.getText()).doubleValue(); }private void handleC(){display.setText("0");firstDigit=true;operator="=";}private void handleBackspace(){String text=display.getText();int i=text.length();if(i>0){text=text.substring(0,i-1);if(text.length()==0){display.setText("0");firstDigit=true;operator="=";}elsedisplay.setText(text);}}private void daoShu(){if (display.getText().equals("0")){display.setText("除数不能为零");System.out.println(1);}else{long l;double d=1/getNumberFromDisplay();l=(long)d;System.out.println(d);System.out.println(l);display.setText(String.valueOf(d));}}}2.CalFrame 类import java.awt.Color;importimport java.awt.event.ActionListener;import java.awt.event.WindowAdapter;import java.awt.event.WindowEvent;import javax.swing.JApplet;import javax.swing.JFrame;public class Test {public static void main(String[] args) {JFrame f=new JFrame();f.getAccessibleContext();Calculator Calculator1=new Calculator(); Calculator1.init();f.getContentPane().add("Center",Calculator1);f.setVisible(true);f.setBounds(300, 200,380,245);f.setBackground(Color.LIGHT_GRAY);f.validate();f.setResizable(false);f.addWindowListener(new WindowAdapter(){public void windowClosing(WindowEvent e){System.exit(0);}});f.setTitle("计算器");}}。

Java计算器源代码(已成功运行)汇总

Java计算器源代码(已成功运行)汇总
Java计算器程序代码
以下为代码:
importjavax.swing.*;
importjava.awt.*;
importjava.awt.event.*;
public class Calculator extends JFrame implements ActionListener
{
private booleandotExist, operated, equaled; //帮助运算的布尔变量
private double storedNumber; //目前的结果private char lastOperator; //表示上一运算符private JTextField operation; //结果栏
private JButton dot, plus, minus, multi, div, sqrt, equal, changePN, clear; //运算符
private JButton[] numbers; //数字
//构造者
public Calculator(
{
setTitle("Calculator";
//初始化变量
dotExist = false; //表示当前的数是否有小数点
operated = false; //表示任意运算符是否被按下equaled = false; //表示等号是否被按下storedNumber = 0;
else if (lastOperator == 's' storedNumber = Math.sqrt(currentNumber; else if (lastOperator == '=' && equaled storedNumber = currentNumber; operation.setText("" + storedNumber; operated = true; lastOperator = operator; } //快捷使用GridBagLayout的方法private void addComponent(GridBagLayout layout, Component component, int row, int col, int width, int height { GridBagConstraints constraints=new GridBagConstraints(; constraints.fill = GridBagConstraints.BOTH; constraints.insets = new Insets(10, 2, 10, 2; constraints.weightx = 100; constraints.weighty = 100; constraints.gridx = col; constraints.gridy = row; constraints.gridwidth = width; constraints.gridheight = height; layout.setConstraints(component, constraints;

计算器 java代码

计算器 java代码

import javax.swing.*;import java.awt.*;import java.awt.event.*;public class Calculater extends JFrame implements ActionListener{private JPanel north, center;private JButton[] buttons = new JButton[20];private JTextField text;private double result;private char modifier = '\0';private boolean flag = false;private int door=0;public Calculater( ){super("计算器");Container c = getContentPane( );c.setLayout(new BorderLayout( ));text = new JTextField(25);north = new JPanel( );north.add(text);center = new JPanel( );center.setLayout(new GridLayout(5,4,2,2));String s[] = {"sqrt","+/-","ON","OFF","7","8","9","/","4","5","6","*","1","2","3","-","0","." ,"=","+"};for(int i=0;i<20;i++){buttons[i] = new JButton(s[i]);center.add(buttons[i]);}for(int i=0;i<20;i++){buttons[i].addActionListener(this);}c.add(north,"North");c.add(center,"Center");}public void setFontAndColor( ){Font f = new Font("宋体",Font.BOLD,20);text.setFont(f);for(int i=0;i<20;i++){buttons[i].setFont(f);buttons[i].setForeground(Color.RED);}}public void actionPerformed(ActionEvent e){String str = e.getActionCommand( );if(("0123456789.".indexOf(str)!=-1)&&door==1){if(flag){text.setText("");flag = false;}text.setText(text.getText()+str);}else if(("+-*/".indexOf(str)!=-1)&&door==1){modifier = str.charAt(0);double num = Double.valueOf(text.getText( ));result = num;text.setText(text.getText( )+str);flag = true;}else if("ON".indexOf(str)!=-1){if(door==0) door=1;text.setText("");}else if("OFF".indexOf(str)!=-1){ if(door==1) door=0;text.setText(" ");}else if(("sqrt".indexOf(str)!=-1)&&door==1){double num=Double.valueOf(text.getText());result=Math.sqrt(num);}else if(("+/-".indexOf(str)!=-1)&&door==1){double num=Double.valueOf(text.getText());result=num*(-1);text.setText(""+result);}else if((str.charAt(0)=='=')&&door==1){if(modifier=='+'){double num = Double.valueOf(text.getText( ));result += num;}if(modifier=='-'){double num = Double.valueOf(text.getText( ));result -= num;}if(modifier=='*'){double num = Double.valueOf(text.getText( ));result *= num;}if(modifier=='/'){double num = Double.valueOf(text.getText( ));result /= num;}text.setText(result+"");modifier = '\0';result = 0;}}public static void main(String[] args){Calculater app = new Calculater( );app.setFontAndColor( );app.setSize(480,320);app.setDefaultCloseOperation(EXIT_ON_CLOSE);app.setVisible(true);}}。

简单的java代码例子

简单的java代码例子

简单的java代码例子1. 使用Java实现一个简单的计算器,可以进行加减乘除运算。

```javaimport java.util.Scanner;public class Calculator {public static void main(String[] args) {Scanner scanner = new Scanner(System.in);System.out.print("请输入第一个数:");double num1 = scanner.nextDouble();System.out.print("请输入运算符(+、-、*、/):");String operator = scanner.next();System.out.print("请输入第二个数:");double num2 = scanner.nextDouble();double result = 0;switch (operator) {case "+":result = num1 + num2;break;case "-":result = num1 - num2;break;case "*":result = num1 * num2;break;case "/":result = num1 / num2;break;default:System.out.println("输入的运算符不正确!");break;}System.out.println("计算结果为:" + result);}}```2. 使用Java实现一个简单的猜数字游戏,随机生成一个1-100之间的整数,让用户猜,直到猜中为止。

```javaimport java.util.Random;import java.util.Scanner;public class GuessNumber {public static void main(String[] args) {Random random = new Random();int number = random.nextInt(100) + 1;Scanner scanner = new Scanner(System.in);int guess;do {System.out.print("请输入你猜的数字(1-100):");guess = scanner.nextInt();if (guess > number) {System.out.println("猜大了!");} else if (guess < number) {System.out.println("猜小了!");}} while (guess != number);System.out.println("恭喜你,猜对了!");}}```3. 使用Java实现一个简单的学生信息管理系统,可以添加、删除、修改、查询学生信息。

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

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

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

计算器(JAVA)源代码

计算器(JAVA)源代码

//定义计算的类import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import javax.swing.JTextField;public class Caculate implements ActionListener { //设置属性private String data;private JTextField text;private String result = "0";private boolean start_new = false;private double last_value = 0;private String ope = "";private double value = 0;public String getResult (){return result;}//定义一个构造方法public Caculate(JTextField text){this.text = text;}@Override//按钮事件处理public void actionPerformed(ActionEvent cal) { // TODO Auto-generated method stubdata = cal.getActionCommand();data = data.trim();if("0123456789".indexOf(data) != -1){numButton(data);}else if (".".indexOf(data) != -1){dotButton(data);}else if ("+-*/".indexOf(data) != -1){operateButton(data);}else if ("=".indexOf(data)!=-1){equalButton();}//System.out.println(data);System.out.println(result);text.setText(result);}//计算程序private void numButton(String da){if(!start_new){result = result + da;}else{result = da;}while (result.startsWith("0")&&!result.startsWith("0.")&&result.length()>0){ result = result.substring(1);}start_new = false;}private void dotButton(String da){if(da.indexOf(".")!= -1){result = result + da;}}private void operateButton(String da){if(result.length()>0){last_value = Double.parseDouble(result);ope = da;start_new = true;}}private void equalButton(){value = Double.parseDouble(result);if(ope.equals("+")){result = String.valueOf(last_value + value);}else if(ope.equals("-")){result = String.valueOf(last_value - value);}else if(ope.equals("*")){result = String.valueOf(last_value * value);}else if(ope.equals("/")){if(value == 0){result = "ERROR";}else{result = String.valueOf(last_value / value);}}// 去掉结尾的“.0000...”if (result.matches(".+\\.0+")) {result = result.substring(0, stIndexOf("."));}// 设置状态start_new = true;ope = "";}}import javax.swing.JTextField;public class Culator {private static final String String = null;JTextField op;private String re;/*** @param args*/public static void main(String[] args) {Culator cul = new Culator();cul.init();// TODO Auto-generated method stub}public void init(){javax.swing.JFrame frame = new javax.swing.JFrame(); frame.setTitle("计算器");java.awt.FlowLayout f1= new java.awt.FlowLayout();frame.setLayout(f1);javax.swing.JMenuBar cai = createMB();frame.setJMenuBar(cai);javax.swing.JButton mc = new javax.swing.JButton("MC");op= new javax.swing.JTextField("0",25);//设置数字从右边开始显示op.setHorizontalAlignment(JTextField.RIGHT);//设置按钮javax.swing.JButton mr = new javax.swing.JButton("MR"); javax.swing.JButton ms = new javax.swing.JButton("MS"); javax.swing.JButton mp = new javax.swing.JButton("M+"); javax.swing.JButton mm = new javax.swing.JButton("M-"); javax.swing.JButton delete = new javax.swing.JButton(" ←"); javax.swing.JButton ce = new javax.swing.JButton("CE "); javax.swing.JButton c = new javax.swing.JButton(" C "); javax.swing.JButton pm = new javax.swing.JButton(" ± "); javax.swing.JButton r = new javax.swing.JButton(" √"); javax.swing.JButton seven = new javax.swing.JButton(" 7 "); javax.swing.JButton eight = new javax.swing.JButton(" 8 "); javax.swing.JButton nine = new javax.swing.JButton(" 9 ");javax.swing.JButton under = new javax.swing.JButton(" / ");javax.swing.JButton percent = new javax.swing.JButton(" % ");javax.swing.JButton four = new javax.swing.JButton(" 4 ");javax.swing.JButton five = new javax.swing.JButton(" 5 ");javax.swing.JButton six = new javax.swing.JButton(" 6 ");javax.swing.JButton and = new javax.swing.JButton(" * ");javax.swing.JButton ds = new javax.swing.JButton("1/x");javax.swing.JButton one = new javax.swing.JButton(" 1 ");javax.swing.JButton two = new javax.swing.JButton(" 2 ");javax.swing.JButton three = new javax.swing.JButton(" 3 ");javax.swing.JButton m = new javax.swing.JButton(" - ");javax.swing.JButton equal = new javax.swing.JButton(" = ");javax.swing.JButton zero = new javax.swing.JButton(" 0 ");javax.swing.JButton dot = new javax.swing.JButton(" . ");javax.swing.JButton plus = new javax.swing.JButton(" + ");//添加按钮frame.add(op);frame.add(mc);frame.add(mr);frame.add(ms);frame.add(mp);frame.add(mm);frame.add(delete);frame.add(ce);frame.add(c);frame.add(pm);frame.add(r);frame.add(seven);frame.add(eight);frame.add(nine);frame.add(under);frame.add(percent);frame.add(four);frame.add(five);frame.add(six);frame.add(and);frame.add(ds);frame.add(one);frame.add(two);frame.add(three);frame.add(m);frame.add(equal);frame.add(zero);frame.add(dot);frame.add(plus);frame.setSize(290,300);//实例化一个Caculate类Caculate cal = new Caculate(op);//增加监听op.addActionListener(cal);mc.addActionListener(cal);mr.addActionListener(cal);ms.addActionListener(cal);mp.addActionListener(cal);mm.addActionListener(cal);delete.addActionListener(cal);ce.addActionListener(cal);c.addActionListener(cal);pm.addActionListener(cal);r.addActionListener(cal);seven.addActionListener(cal);eight.addActionListener(cal);nine.addActionListener(cal);under.addActionListener(cal); percent.addActionListener(cal);four.addActionListener(cal);five.addActionListener(cal);six.addActionListener(cal);and.addActionListener(cal);ds.addActionListener(cal);one.addActionListener(cal);two.addActionListener(cal);three.addActionListener(cal);m.addActionListener(cal);equal.addActionListener(cal);zero.addActionListener(cal);dot.addActionListener(cal);plus.addActionListener(cal);frame.setDefaultCloseOperation(3); frame.setResizable(false);frame.setVisible(true);}//创建一个设置TextField窗口容的函数//public void setOp(String re){// op.setText(re);//}//创建一个常带有菜单的菜单条,就加到JFrame上显示private javax.swing.JMenuBar createMB(){//创建菜单条javax.swing.JMenuBar mb = new javax.swing.JMenuBar();//创建查看菜单javax.swing.JMenu view = new javax.swing.JMenu("查看(V)");//创建菜单项javax.swing.JMenuItem biaozhun = new javax.swing.JMenuItem("标准型"); javax.swing.JMenuItem kexue = new javax.swing.JMenuItem("科学型"); javax.swing.JMenuItem chengxu = new javax.swing.JMenuItem("程序员"); javax.swing.JMenuItem tongji = new javax.swing.JMenuItem("统计信息"); javax.swing.JMenuItem history = new javax.swing.JMenuItem("历史");//将菜单项添加到菜单上view.add(biaozhun);view.add(kexue);view.add(chengxu);view.add(tongji);view.add(history);//创建编辑菜单javax.swing.JMenu operation = new javax.swing.JMenu("编辑(O)");//创建菜单项javax.swing.JMenuItem copy = new javax.swing.JMenuItem("复制"); javax.swing.JMenuItem paste = new javax.swing.JMenuItem("黏贴"); javax.swing.JMenuItem hr = new javax.swing.JMenuItem("历史记录");//将菜单项添加到菜单上operation.add(copy);operation.add(paste);operation.add(hr);//创建帮助菜单javax.swing.JMenu help = new javax.swing.JMenu("帮助(H)");//创建帮助菜单项javax.swing.JMenuItem vh = new javax.swing.JMenuItem("查看帮助"); javax.swing.JMenuItem about = new javax.swing.JMenuItem("关于计算器"); //将菜单项添加到菜单上help.add(vh);help.add(about);//加上一个分隔条help.addSeparator();//将菜单添加到菜单条上mb.add(view);mb.add(operation);mb.add(help);return mb;} }。

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

北邮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计算器源代码

计算器源代码一、计算器源代码文件名: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.event.ActionEvent;import java.awt.event.ActionListener;import javax.swing.*;import java.awt.*;import java.math.BigDecimal;import java.math.MathContext;import java.math.RoundingMode;import java.awt.Color;/*** java版计算器*/public class Calculator extends JFrame {final int WIN_W = 250, WIN_H = 250;JPanel myPanel, panelSuper;public Calculator() {// 主面板panelSuper = new JPanel();panelSuper.setLayout(null);// 设置窗口位置double width = Toolkit.getDefaultToolkit().getScreenSize().width; double height =Toolkit.getDefaultToolkit().getScreenSize().height;this.setBounds((int) (width - WIN_W) / 2, (int) (height - WIN_H) / 2,WIN_W, WIN_H);// 窗口配置this.setTitle("java版计算器");this.validate();this.setResizable(false);this.setVisible(true);this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);// 添加计算器按钮面板myPanel = new MyPanel();this.add(myPanel, BorderLayout.CENTER);}public static void main(String[] args) {new Calculator();}/*** 计算器按钮面板类*/class MyPanel extends JPanel implements ActionListener {JButton button1, button2, button3, button4, button5, button6, button7,button8, button9, button0, buttonJia, buttonJian, buttonCheng,buttonChu, buttonDeng, buttonDian, buttonC, buttonDel, buttonZF, buttonGH;JTextField jTextField; // 计算器显示屏char oper; // 操作符String key, allKey = "1234567890.±del", jjccKey = " -*/";BigDecimal d1, d2;boolean first;public MyPanel() {// 设置布局this.setLayout(new FlowLayout(FlowLayout.LEFT, 4, 5));// 计算器显示屏jTextField = new JTextField(21);jTextField.setHorizontalAlignment(JTextField.RIGHT);jTextField.setEditable(false);jTextField.setBackground(new Color(255, 255, 255));jTextField.setText("0");this.add(jTextField);// 计算器按钮button1 = new JButton("1");button2 = new JButton("2");button3 = new JButton("3");button4 = new JButton("4");button5 = new JButton("5");button6 = new JButton("6");button7 = new JButton("7");button8 = new JButton("8");button9 = new JButton("9");button0 = new JButton("0");buttonJia = new JButton(" ");buttonJian = new JButton("-");buttonCheng = new JButton("*");buttonChu = new JButton("/");buttonDeng = new JButton("=");buttonDian = new JButton(".");buttonDel = new JButton("del");buttonC = new JButton("c");buttonZF = new JButton("±");buttonGH = new JButton("√");button1.setPreferredSize(new Dimension(55, 30));button2.setPreferredSize(new Dimension(55, 30));button3.setPreferredSize(new Dimension(55, 30));button4.setPreferredSize(new Dimension(55, 30));button5.setPreferredSize(new Dimension(55, 30));button6.setPreferredSize(new Dimension(55, 30));button7.setPreferredSize(new Dimension(55, 30));button8.setPreferredSize(new Dimension(55, 30));button9.setPreferredSize(new Dimension(55, 30));button0.setPreferredSize(new Dimension(55, 30));buttonJia.setPreferredSize(new Dimension(55, 30)); buttonJian.setPreferredSize(new Dimension(55, 30)); buttonCheng.setPreferredSize(new Dimension(55, 30)); buttonChu.setPreferredSize(new Dimension(55, 30)); buttonDeng.setPreferredSize(new Dimension(55, 30)); buttonDian.setPreferredSize(new Dimension(55, 30)); buttonDel.setPreferredSize(new Dimension(55, 30)); buttonC.setPreferredSize(new Dimension(55, 30));buttonZF.setPreferredSize(new Dimension(55, 30));buttonGH.setPreferredSize(new Dimension(55, 30)); this.add(buttonDel);this.add(buttonC);this.add(buttonZF);this.add(buttonGH);this.add(button1);this.add(button2);this.add(button3);this.add(buttonJia);this.add(button4);this.add(button5);this.add(button6);this.add(buttonJian);this.add(button7);this.add(button8);this.add(button9);this.add(buttonCheng);this.add(button0);this.add(buttonDian);this.add(buttonDeng);this.add(buttonChu);buttonDel.addActionListener(this);buttonC.addActionListener(this);buttonZF.addActionListener(this);buttonGH.addActionListener(this);button1.addActionListener(this);button2.addActionListener(this);button3.addActionListener(this);button4.addActionListener(this);button5.addActionListener(this);button6.addActionListener(this);button7.addActionListener(this);button8.addActionListener(this);button9.addActionListener(this);button0.addActionListener(this);buttonJia.addActionListener(this);buttonJian.addActionListener(this);buttonCheng.addActionListener(this);buttonChu.addActionListener(this);buttonDeng.addActionListener(this);buttonDian.addActionListener(this);// 计算器初始化init();}/*** 计算器初始化*/public void init() {d1 = new BigDecimal("0");d1 = new BigDecimal("0");key = "=";oper = '=';jTextField.setText("0");first = true; // 用于标记是否进行连续操作(例如按键顺序为“9*9====”,第一次等于first由true变为false,如果!first,按等号相当于用上一次的结果与第二个操作数相乘)}/*** 按钮监听*/public void actionPerformed(ActionEvent e) {JButton b = (JButton) e.getSource();if (b == buttonDian) { // 按下.jTextField.setText(jTextField.getText() ".");if (first) {d2 = d1 = getNum();} else {d2 = getNum();}} else if (b == buttonZF) {// 按下±BigDecimal d = getNum();d = new BigDecimal("0").subtract(d);setFormatNum(d);if (first) {d2 = d1 = getNum();} else {d2 = getNum();}} else if (b == buttonDel) {// 按下delif (jTextField.getText().length() == 1|| jTextField.getText().length() == 2&& jTextField.getText().startsWith("-")) { jTextField.setText("0");} else {String s = jTextField.getText();s = s.substring(0, s.length() - 1);if (s.endsWith("E ") || s.endsWith("E-"))s = s.substring(0, s.length() - 2);jTextField.setText(s);if (first) {d2 = d1 = getNum();} else {d2 = getNum();}}} else if (b == buttonC) {// 按下cinit();} else if (b == buttonJia) {// 按下BigDecimal s;if (!first && allKey.indexOf(key) >= 0) {if (oper == '-' || oper == '/') {s = operate(d1, oper, d2);} else {s = operate(d2, oper, d1);}setFormatNum(s);}// 如果不是第一次,且上一次操作是对数字进行操作else {first = false;}d2 = d1 = getNum();// System.out.print("111我执行啦\n");oper = ' ';} else if (b == buttonJian) {// 按下-BigDecimal s;if (!first && allKey.indexOf(key) >= 0) {s = operate(d1, oper, d2);setFormatNum(s);}// 如果不是第一次,且上一次操作是对数字进行操作 else {first = false;}d2 = d1 = getNum();oper = '-';} else if (b == buttonCheng) {// 按下*BigDecimal s;if (!first && allKey.indexOf(key) >= 0) {if (oper == '-' || oper == '/') {s = operate(d1, oper, d2);} else {s = operate(d2, oper, d1);}setFormatNum(s);}// 如果不是第一次,且上一次操作是对数字进行操作 else {first = false;}d2 = d1 = getNum();oper = '*';} else if (b == buttonChu) {// 按下/BigDecimal s;if (!first && allKey.indexOf(key) >= 0) {s = operate(d1, oper, d2);setFormatNum(s);}// 如果不是第一次,且上一次操作是对数字进行操作 else {first = false;}d2 = d1 = getNum();oper = '/';} else if (b == buttonGH) {// 按下平方根if (jTextField.getText().startsWith("-")) {init();return;}BigDecimal d = getNum();MathContext mc = new MathContext(10, RoundingMode.HALF_DOWN);d = new BigDecimal(Math.sqrt(d.doubleValue()), mc);setFormatNum(d);if (first) {d2 = d1 = getNum();} else {d2 = getNum();}} else if (b == buttonDeng) {// 按下=BigDecimal s = null;d2 = getNum();if (!key.equals("=")) {s = operate(d1, oper, d2);} else {s = operate(d2, oper, d1);}if (oper != '=' && !key.equals("=")) {// 上一次操作为 -*/d1 = getNum();}setFormatNum(s);first = true;} else { // 按下其他按钮if (this.jTextField.getText().equals("0")|| allKey.indexOf(key) == -1) {this.jTextField.setText(b.getText());} else {this.jTextField.setText(jTextField.getText()b.getText());}if (first) {d2 = d1 = getNum();} else {d2 = getNum();}// d2作被加数:d2 d1}key = b.getText();}/*** 获取操作数** @return 操作数*/public BigDecimal getNum() {BigDecimal d = new BigDecimal(jTextField.getText());return d;}public void setFormatNum(BigDecimal dd) {MathContext mc = new MathContext(18, RoundingMode.HALF_DOWN);BigDecimal d = new BigDecimal(dd.toString(), mc);String num = d.toString();if (num.endsWith(".0"))num = num.replaceAll("\\.0", "");this.jTextField.setText(num);}/*** 计算** @param a1* 操作数1* @param c* 操作符* @param a2* 操作数2* @return*/public BigDecimal operate(BigDecimal a1, char c, BigDecimal a2) {MathContext mc = new MathContext(10, RoundingMode.HALF_DOWN); switch (c) {case ' ':return a1.add(a2);case '-':return a1.subtract(a2);case '*':return a1.multiply(a2);case '/':if (pareTo(new BigDecimal("0")) == 0) {init();return new BigDecimal("0"); }return a1.divide(a2, mc);default:return a2;}}}}。

java计算器代码

java计算器代码
}
/*************标准界面设计***************/
public void go() {
frame = new JFrame("计算器");
JMenuBar mB = new JMenuBar();
frame.setJMenuBar(mB);
/********* 菜单项 ***********/
menuItem1.addActionListener(this);
menuItem1.setMnemonic(KeyEvent.VK_O);
menuItem1.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_1,
ActionEvent.ALT_MASK));
menuItem.setActionCommand("历史结果");
submenu.add(menuItem);
// 帮助项
menu = new JMenu("帮助");
mB.add(menu);
menuItem = new JMenuItem("关于计算器");
menuItem.setActionCommand("粘贴");
menu.add(menuItem);
menu.addSeparator();// 加入分隔线
JMenu submenu = new JMenu("历史记录");
menu.add(submenu);
menuItem = new JMenuItem("历史计算");
text.setText(" 很抱歉计算器功能正在完善中" + "\n" + " 暂时无法使用此功能!");

科学计算器Java源代码

科学计算器Java源代码
setResizable(false); //设置此图形界面是不可以改变大小的
pack();
setVisible(trห้องสมุดไป่ตู้e);
}
public void setup() //搭建次程序的图形应用界面
{
pan1.setLayout(new BorderLayout());
Labelnow.setFont(wordFont1);
Labelnow.setBackground(Color.gray);
pan3.add(Labelnow);
Labeltime.setBackground(Color.gray);
Labeltime.setFont(wordFont1);
System.out.println("即将计算的表达式是:"+QU);
Labelnow.setText("计算程序正在运行");
appendchar( button20.getLabel());
appendchar( countall ( QU ) );
private Button button9=new Button("9");
private Button button10=new Button("0");
private Button button11=new Button("+");
private Button button12=new Button("-");
{
super("我的科学计算器");
setup();

java计算器代码

java计算器代码

import java.awt.*;import java.awt.event.*;import javax.swing.*;public class Calculator extends JFrame{private Container container;//框架private JTextField tf;//定义文本框private Panel panel;private String cmd;private double result;//运算结果private boolean start;//运算开始判断Calculator(){super("李正刚-java简易计算器计算器");container = getContentPane();container.setLayout(new BorderLayout());//添加文本框tf = new JTextField("0.0");container.add(tf,BorderLayout.NORTH);tf.setHorizontalAlignment(JTextField.RIGHT);tf.setEditable(false);//嵌套容器panel = new Panel();container.add(panel);start = true;result = 0;//最后运算等号cmd = "=";ActionListener insert = new InsertAction(); ActionListener command = new CommandAction();//调用创建Button方法addButton("1",insert);addButton("2",insert);addButton("3",insert);addButton("0",insert);addButton("*",command);addButton("Back",insert);addButton("4",insert);addButton("5",insert);addButton("6",insert);addButton("+",command);addButton("/",command);addButton("Clear",insert);addButton("7",insert);addButton("8",insert);addButton("9",insert);addButton("-",command);addButton(".",insert);addButton("=",command);setSize(400,200);}private void addButton(String str,ActionListener listener){//添加Button方法(操作类型、注册监听器)JButton button=new JButton(str);button.addActionListener(listener);panel.setLayout(new GridLayout(3,6));panel.add(button);}private class InsertAction implements ActionListener{//插入,insertpublic void actionPerformed(ActionEvent event){String input=event.getActionCommand();if (start){tf.setText("");start=false;}if(input.equals("Back")){String str=tf.getText();if(str.length()>0)tf.setText(str.substring(0,str.length()-1)); }else if(input.equals("Clear")){tf.setText("0");start=true;}elsetf.setText(tf.getText()+input);}}private class CommandAction implements ActionListener{//计算,commandpublic void actionPerformed(ActionEvent e){String command=e.getActionCommand();if(start){cmd=command;}else{calculate(Double.parseDouble(tf.getText()));cmd=command;start=true;}}}public void calculate(double x){//加减乘除运算if (cmd.equals("+")) result+=x;else if (cmd.equals("-")) result-=x;else if (cmd.equals("*")) result*=x;else if (cmd.equals("/")) result/=x;else if (cmd.equals("=")) result= x;tf.setText(""+ result);}public static void main(String []args){Calculator mycalculator=new Calculator();mycalculator.setLocation(300,300);mycalculator.setVisible(true);}}。

Java科学计算器程序代码

Java科学计算器程序代码

Java科学计算器程序代码————————————————————————————————作者:————————————————————————————————日期:计算器布局显示:功能举例:①13+20=33②—7*14=—98:先输入7,再单击—/+将其变成负数,然后依次单击×号、14与=③7!=5040④sin30°=0。

5:先输入30,然后按下′″按钮转换成角度值,再按下sin即可显示结果⑤sqrt(4)=2:利用鼠标点击4后再点击sqrt按键即可显示结果⑥2*π=6.2832……源程序如下:import java.awt。

BorderLayout;import java.awt。

Color;import java.awt.Dimension;import java.awt。

Font;import java.awt。

GridLayout;import java。

awt.event。

ActionEvent;import java.awt。

event.ActionListener;import java.text。

DecimalFormat;import javax。

swing。

BorderFactory;import javax.swing。

ButtonGroup;import javax.swing。

JButton;import javax。

swing.JCheckBoxMenuItem;import javax。

swing。

JFrame;import javax.swing。

JMenu;import javax.swing.JMenuBar;import javax.swing.JMenuItem;import javax.swing。

JPanel;import javax。

swing。

JRadioButtonMenuItem;import javax.swing。

(java版的计算器-带事件的)

(java版的计算器-带事件的)

程序功能简介:从最基本的加、减、乘、除,到基本数学函数处理,再到数的进制转换处理。

代码如下/*文件名:Calculator.java*说明:简易科学计算器*/import java.awt.*;import java.awt.event.*;import javax.swing.*;public class Calculator extends Frame implements ActionListener, WindowListener{private Container container;private GridBagLayout layout;private GridBagConstraints constraints;private JTextField displayField; //计算结果显示区private String lastCommand; //保存+,-,*,/,=命令0private double result; //保存计算结果private boolean start; //判断是否为数字的开始private JMenuBar menubar;private JMenuItem m_exit,m2_ejz,m2_bjz;private Dialog dialog;private Label label_dialog;private JButton button_sqrt,button_plusminus,button_CE,button_cancel,button_1,button_2,button_3,button_4,button_5,button_6,button_7,button_8,button_9,button_0,button_plus,button_minus,button_multiply,button_divide,button_point,button_equal,button_log,button_tan,button_cos,button_sin,button_exp;public Calculator() //构造方法设置布局、为按钮注册事件监听器{super("Calculator");this.setLocation(240,200);this.setSize(350,300);this.setResizable(true);this.setLayout(new GridLayout(7,1));this.addmyMenu(); //调用成员方法添加菜单displayField=new JTextField(30);this.add(displayField);displayField.setEditable(true);start=true;result=0;lastCommand = "=";JPanel panel0=new JPanel();panel0.setLayout(new GridLayout(1,4,4,4));JPanel panel1=new JPanel();panel1.setLayout(new GridLayout(1,5,4,4));this.add(panel1);button_sqrt=new JButton("sqrt");button_plusminus=new JButton("+/-");button_exp=new JButton("exp");button_CE=new JButton("退格");button_cancel=new JButton("C");JPanel panel2=new JPanel();panel2.setLayout(new GridLayout(1,5,4,4));this.add(panel2);button_7=new JButton("7");button_8=new JButton("8");button_9=new JButton("9");button_log=new JButton("log");button_divide=new JButton("/");JPanel panel3=new JPanel();panel3.setLayout(new GridLayout(1,5,4,4));this.add(panel3);button_4=new JButton("4");button_5=new JButton("5");button_6=new JButton("6");button_tan=new JButton("tan");button_multiply=new JButton("*");JPanel panel4=new JPanel();panel4.setLayout(new GridLayout(1,5,4,4));this.add(panel4);button_1=new JButton("1");button_2=new JButton("2");button_3=new JButton("3");button_cos=new JButton("cos");button_minus=new JButton("-");JPanel panel5=new JPanel();panel5.setLayout(new GridLayout(1,5,4,4));this.add(panel5);button_0=new JButton("0");button_point=new JButton(".");button_equal=new JButton("=");button_sin=new JButton("sin");button_plus=new JButton("+");panel1.add(button_sqrt);panel1.add(button_plusminus);panel1.add(button_exp);panel1.add(button_CE);panel1.add(button_cancel);panel2.add(button_7);panel2.add(button_8);panel2.add(button_9);panel2.add(button_log);panel2.add(button_divide);panel3.add(button_4);panel3.add(button_5);panel3.add(button_6);panel3.add(button_tan);panel3.add(button_multiply);panel4.add(button_1);panel4.add(button_2);panel4.add(button_3);panel4.add(button_cos);panel4.add(button_minus);panel5.add(button_0);panel5.add(button_point);panel5.add(button_equal);panel5.add(button_sin);panel5.add(button_plus);button_sqrt.addActionListener(this);button_plusminus.addActionListener(this);button_exp.addActionListener(this);button_CE.addActionListener(this);button_cancel.addActionListener(this);button_7.addActionListener(this);button_8.addActionListener(this);button_9.addActionListener(this);button_log.addActionListener(this);button_divide.addActionListener(this);button_4.addActionListener(this);button_5.addActionListener(this);button_6.addActionListener(this);button_tan.addActionListener(this);button_multiply.addActionListener(this);button_1.addActionListener(this);button_2.addActionListener(this);button_3.addActionListener(this);button_cos.addActionListener(this);button_minus.addActionListener(this);button_0.addActionListener(this);button_point.addActionListener(this);button_equal.addActionListener(this);button_sin.addActionListener(this);button_plus.addActionListener(this);this.addWindowListener(new WinClose()); //注册窗口监听器this.setVisible(true);}private void addmyMenu() //菜单的添加{JMenuBar menubar=new JMenuBar();this.add(menubar);JMenu m1=new JMenu("选项");JMenu m2=new JMenu("进制转换");JMenuItem m1_exit=new JMenuItem("退出");m1_exit.addActionListener(this);JMenuItem m2_ejz=new JMenuItem("二进制");m2_ejz.addActionListener(this);JMenuItem m2_bjz=new JMenuItem("八进制");m2_bjz.addActionListener(this);JMenu m3 = new JMenu(" 帮助");JMenuItem m3_Help = new JMenuItem("用法");m3_Help.addActionListener(this);dialog = new Dialog(this,"提示",true); //模式窗口dialog.setSize(240,80);label_dialog = new Label("",Label.CENTER); //标签的字符串为空,居中对齐dialog.add(label_dialog);dialog.addWindowListener(this); //为对话框注册窗口事件监听器m1.add(m1_exit);menubar.add(m1);m2.add(m2_ejz);m2.add(m2_bjz);menubar.add(m2);m3.add(m3_Help);menubar.add(m3); }public void actionPerformed(ActionEvent e) //按钮的单击事件处理方法{if(e.getSource().equals(button_1)||e.getSource().equals(button_2)||e.getSource().equals(button_3)||e.getSource().equals(button_4)||e.getSource().equals(button_5)|| e.getSource().equals(button_6)||e.getSource().equals(button_7)|| e.getSource().equals(button_8)||e.getSource().equals(button_9) ||e.getSource().equals(button_0)||e.getSource().equals(button_point)||e.getSource().equals(button_plusminus)||e.getSource().equals(button_cancel)||e.getSource().equals(button_CE)){ //非运算符的处理方法String input=e.getActionCommand();if (start){displayField.setText("");start=false;if(input.equals("+/-"))displayField.setText(displayField.getText()+"-");}if(!input.equals("+/-")){String str=displayField.getText();if(input.equals("退格")) //退格键的实现方法{if(str.length()>0)displayField.setText(str.substring(0,str.length()-1));}else if(input.equals("C")) //清零键的实现方法{displayField.setText("0");start=true;}elsedisplayField.setText(displayField.getText()+input);}}else if (e.getActionCommand()=="二进制") //二进制的转换{int n=Integer.parseInt(displayField.getText());displayField.setText(Integer.toBinaryString(n));}else if (e.getActionCommand()=="八进制") //八进制的转换{int n=Integer.parseInt(displayField.getText());displayField.setText(Integer.toOctalString(n));}else if (e.getActionCommand()=="退出") //选项中退出的处理方法{System.exit(0);}else if (e.getActionCommand()=="用法") //按下'帮助'菜单栏中用法的处理方法{label_dialog.setText("sqrt,exp等键是先输运算符再输数字\n");dialog.setLocation(400,250);dialog.setVisible(true);}else //各运算符的识别{String command=e.getActionCommand();if(start){lastCommand=command;}else{calculate(Double.parseDouble(displayField.getText()));lastCommand=command;start=true;}}}public void calculate(double x) //各运算符的具体运算方法double d=0;if (lastCommand.equals("+"))result+= x;else if (lastCommand.equals("-"))result-=x;else if (lastCommand.equals("*"))result*=x;else if (lastCommand.equals("/"))result/=x;else if (lastCommand.equals("="))result=x;else if (lastCommand.equals("sqrt")){d=Math.sqrt(x);result=d;}else if (lastCommand.equals("exp")){d=Math.exp(x);result=d;}else if (lastCommand.equals("log")){d=Math.log(x);result=d;}else if (lastCommand.equals("tan")){d=Math.tan(x);result=d;}else if (lastCommand.equals("cos")){d=Math.cos(x);result=d;}else if (lastCommand.equals("sin")){d=Math.sin(x);result=d;}displayField.setText(""+ result);}public void windowClosing(WindowEvent e){if(e.getSource()==dialog)dialog.setVisible(false); //隐藏对话框 elseSystem.exit(0);public void windowOpened(WindowEvent e) { }public void windowActivated(WindowEvent e) { }public void windowDeactivated(WindowEvent e) { }public void windowClosed(WindowEvent e) { }public void windowIconified(WindowEvent e) { }public void windowDeiconified(WindowEvent e) { }public static void main(String args[]){Calculator calculator=new Calculator();}}class WinClose implements WindowListener{public void windowClosing(WindowEvent e) //单击窗口关闭按钮时触发并执行实现窗口监听器接口中的方法{System.exit(0); //结束程序运行}public void windowOpened(WindowEvent e){}public void windowActivated(WindowEvent e){}public void windowDeactivated(WindowEvent e){}public void windowClosed(WindowEvent e){}public void windowIconified(WindowEvent e){}public void windowDeiconified(WindowEvent e){}}运行结果截图:程序功能实现:1.运用两个面板的叠加做出界面。

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

计算器布局显示:功能举例:①13+20=33②-7*14=-98:先输入7,再单击-/+将其变成负数,然后依次单击×号、14与=③7!=5040④sin30°=0.5:先输入30,然后按下′″按钮转换成角度值,再按下sin即可显示结果⑤sqrt(4)=2:利用鼠标点击4后再点击sqrt按键即可显示结果⑥2*π=6.2832……源程序如下:import java.awt.BorderLayout;import java.awt.Color;import java.awt.Dimension;import java.awt.Font;import java.awt.GridLayout;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.text.DecimalFormat;import javax.swing.BorderFactory;import javax.swing.ButtonGroup;import javax.swing.JButton;import javax.swing.JCheckBoxMenuItem;import javax.swing.JFrame;import javax.swing.JMenu;import javax.swing.JMenuBar;import javax.swing.JMenuItem;import javax.swing.JPanel;import javax.swing.JRadioButtonMenuItem;import javax.swing.JTextField;public class Calucator extends JFrame {private JTextField tf;private JPanel panel1, panel2, panel3, panel4;private JMenuBar myBar;private JMenu menu1, menu2, menu3;private JMenuItem editItem1, editItem2, help1, help2, help3;private JRadioButtonMenuItem seeItem1, seeItem2;//单选框private JCheckBoxMenuItem seeItem3;//复选框private ButtonGroup bgb;private String back;private boolean IfResult = true, flag = false;private String oper = "=";private double result = 0;private Num numActionListener;private DecimalFormat df;public Calucator(){super("科学计算器");//设置标题栏df = new DecimalFormat("#.####");//保留四位小数this.setLayout(new BorderLayout(10, 5));panel1 = new JPanel(new GridLayout(1, 3, 10, 10));panel2 = new JPanel(new GridLayout(5, 6, 5, 5));//5行6列panel3 = new JPanel(new GridLayout(5, 1, 5, 5));panel4 = new JPanel(new BorderLayout(5, 5));/***菜单栏*/myBar = new JMenuBar();menu1 = new JMenu("编辑(E)");menu2 = new JMenu("查看(V)");menu3 = new JMenu("帮助(H)");menu1.setFont(new Font("宋体", Font.PLAIN, 12));menu2.setFont(new Font("宋体", Font.PLAIN, 12));menu3.setFont(new Font("宋体", Font.PLAIN, 12));/***编辑栏*/editItem1 = new JMenuItem("复制(C) Ctrl+C");editItem2 = new JMenuItem("粘贴(P) Ctrl+V");editItem1.setFont(new Font("宋体",Font.PLAIN,12)); editItem2.setFont(new Font("宋体",Font.PLAIN,12));/***查看栏*/seeItem1 = new JRadioButtonMenuItem("科学型(T)"); seeItem2 = new JRadioButtonMenuItem("标准型(S)"); seeItem3 = new JCheckBoxMenuItem("数字分组(I)");seeItem1.setFont(new Font("宋体",Font.PLAIN,12)); seeItem2.setFont(new Font("宋体",Font.PLAIN,12)); seeItem3.setFont(new Font("宋体",Font.PLAIN,12));/***帮助栏*/help1 = new JMenuItem("帮助主题(H)");help2 = new JMenuItem("关于计算器(A)");help1.setFont(new Font("宋体",Font.PLAIN,12)); help2.setFont(new Font("宋体",Font.PLAIN,12));bgb = new ButtonGroup();//选项组menu1.add(editItem1);menu1.add(editItem2);menu2.add(seeItem1);menu2.add(seeItem2);menu2.addSeparator();//添加一条分割线menu2.add(seeItem3);menu3.add(help1);menu3.addSeparator();//添加一条分割线menu3.add(help2);myBar.add(menu1);myBar.add(menu2);myBar.add(menu3);this.setJMenuBar(myBar);numActionListener = new Num();//实现数字监听/***文本域,即为计算器的屏幕显示区域*/tf = new JTextField();tf.setEditable(false);//文本区域不可编辑tf.setBackground(Color.white);//文本区域的背景色tf.setHorizontalAlignment(JTextField.RIGHT);//文字右对齐tf.setText("0");tf.setBorder(BorderFactory.createLoweredBevelBorder());init();//对计算器进行初始化}/***初始化操作*添加按钮*/private void init(){addButton(panel1, "Backspace", new Clear(), Color.red);addButton(panel1, "CE", new Clear(), Color.red);addButton(panel1, "C", new Clear(), Color.red);addButton(panel2, "1/x", new Signs(), Color.magenta);addButton(panel2, "log", new Signs(), Color.magenta);addButton(panel2, "7", numActionListener, Color.blue);addButton(panel2, "8", numActionListener, Color.blue);addButton(panel2, "9", numActionListener, Color.blue);addButton(panel2, "÷", new Signs(), Color.red);addButton(panel2, "n!", new Signs(), Color.magenta);addButton(panel2, "sqrt", new Signs(), Color.magenta);addButton(panel2, "4", numActionListener, Color.blue);addButton(panel2, "5", numActionListener, Color.blue);addButton(panel2, "6", numActionListener, Color.blue);addButton(panel2, "×", new Signs(), Color.red);addButton(panel2, "sin", new Signs(), Color.magenta);addButton(panel2, "x^2", new Signs(), Color.magenta);addButton(panel2, "1", numActionListener, Color.blue);addButton(panel2, "2", numActionListener, Color.blue);addButton(panel2, "3", numActionListener, Color.blue);addButton(panel2, "-", new Signs(), Color.red);addButton(panel2, "cos", new Signs(), Color.magenta);addButton(panel2, "x^3", new Signs(), Color.magenta);addButton(panel2, "0", numActionListener, Color.blue);addButton(panel2, "-/+", new Clear(), Color.blue);addButton(panel2, ".", new Dot(), Color.blue);addButton(panel2, "+", new Signs(), Color.red);addButton(panel2, "tan", new Signs(), Color.magenta);addButton(panel2, "%", new Signs(), Color.magenta);addButton(panel2, "π", numActionListener, Color.orange);addButton(panel2, "e", numActionListener, Color.orange);addButton(panel2, "′″", new Signs(), Color.orange);addButton(panel2, "=", new Signs(), Color.red);JButton btns = new JButton("计算器");btns.setBorder(BorderFactory.createLoweredBevelBorder());btns.setEnabled(false);//按钮不可操作btns.setPreferredSize(new Dimension(20, 20));panel3.add(btns);//加入按钮addButton(panel3, "MC", null, Color.red);addButton(panel3, "MR", null, Color.red);addButton(panel3, "MS", null, Color.red);addButton(panel3, "M+", null, Color.red);panel4.add(panel1, BorderLayout.NORTH);panel4.add(panel2, BorderLayout.CENTER);this.add(tf, BorderLayout.NORTH);this.add(panel3, BorderLayout.WEST);this.add(panel4);pack();this.setResizable(false);//窗口不可改变大小this.setLocation(300, 200);this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);}/***统一设置按钮的的使用方式*@param panel*@param name*@param action*@param color*/private void addButton(JPanel panel, String name, ActionListener action, Color color){JButton bt = new JButton(name);panel.add(bt);//在面板上增加按钮bt.setForeground(color);//设置前景(字体)颜色bt.addActionListener(action);//增加监听事件}/***计算器的基础操作(+-×÷)*@param x*/private void getResult (double x){if(oper == "+"){result += x;}else if(oper == "-"){result -= x;}else if(oper == "×"){result *= x;}else if(oper == "÷"){result /= x;}else if(oper == "="){result = x;}tf.setText(df.format(result));}/***运算符号的事件监听*/class Signs implements ActionListener{public void actionPerformed(ActionEvent e) {/** 用ActionEvent对象的getActionCommand()方法* 取得与引发事件对象相关的字符串*/String str = e.getActionCommand();/* sqrt求平方根 */if(str.equals("sqrt")){double i = Double.parseDouble(tf.getText());if(i>=0){/** String.valueOf() 转换为字符串* df.format() 按要求保留四位小数* Math.sqrt() 求算数平方根*/tf.setText(String.valueOf(df.format(Math.sqrt(i))));}else{tf.setText("负数不能开平方根");}}/* log求常用对数 */else if(str.equals("log")){double i = Double.parseDouble(tf.getText());if(i>0){tf.setText(String.valueOf(df.format(Math.log(i))));}else{tf.setText("负数不能求对数");}}/* %求百分比 */else if(str.equals("%")){tf.setText(df.format(Double.parseDouble(tf.getText()) / 100)); }/* 1/x求倒数 */else if(str.equals("1/x")){if(Double.parseDouble(tf.getText()) == 0){tf.setText("除数不能为零");}else{tf.setText(df.format(1 / Double.parseDouble(tf.getText())));}}/* sin求正弦函数 */else if(str.equals("sin")){double i = Double.parseDouble(tf.getText());tf.setText(String.valueOf(df.format(Math.sin(i))));}/* cos求余弦函数 */else if(str.equals("cos")){double i = Double.parseDouble(tf.getText());tf.setText(String.valueOf(df.format(Math.cos(i))));}/* tan求正切函数 */else if(str.equals("tan")){double i = Double.parseDouble(tf.getText());tf.setText(String.valueOf(df.format(Math.tan(i))));}/* n!求阶乘 */else if(str.equals("n!")){double i = Double.parseDouble(tf.getText());if((i%2==0)||(i%2==1))//判断为整数放进行阶乘操作{int j = (int)i;//强制类型转换int result=1;for(int k=1;k<=j;k++)result *= k;tf.setText(String.valueOf(result));}else{tf.setText("无法进行阶乘");}}/* x^2求平方 */else if(str.equals("x^2")){double i = Double.parseDouble(tf.getText());tf.setText(String.valueOf(df.format(i*i)));}/* x^3求立方 */else if(str.equals("x^3")){double i = Double.parseDouble(tf.getText());tf.setText(String.valueOf(df.format(i*i*i))); }/* ′″角度转换 *//***将角度值转换成弧度值,方便三角函数的计算*/else if(str.equals("′″")){double i = Double.parseDouble(tf.getText());tf.setText(String.valueOf(i/180*Math.PI));}else{if(flag){IfResult = false;}if(IfResult){oper = str;}else{getResult(Double.parseDouble(tf.getText()));oper = str;IfResult = true;}}}}/***清除按钮的事件监听*/class Clear implements ActionListener{public void actionPerformed(ActionEvent e) {/** 用ActionEvent对象的getActionCommand()方法* 取得与引发事件对象相关的字符串*/String str = e.getActionCommand();if(str == "C"){tf.setText("0");IfResult = true;result = 0;}else if(str == "-/+"){double i = 0 - Double.parseDouble(tf.getText().trim());tf.setText(df.format(i));}else if(str == "Backspace"){if(Double.parseDouble(tf.getText()) > 0){if(tf.getText().length() > 1){tf.setText(tf.getText().substring(0,tf.getText().length() - 1));//使用退格删除最后一位字符}else{tf.setText("0");IfResult = true;}}else{if(tf.getText().length() > 2){tf.setText(tf.getText().substring(0,tf.getText().length() - 1));}else{tf.setText("0");IfResult = true;}}}else if(str == "CE"){tf.setText("0");IfResult = true;}}}/***数字输入的事件监听*/class Num implements ActionListener{public void actionPerformed(ActionEvent e) { String str = e.getActionCommand();if(IfResult){tf.setText("");IfResult = false;}if(str=="π"){tf.setText(String.valueOf(Math.PI));}else if(str=="e"){tf.setText(String.valueOf(Math.E));}else{tf.setText(tf.getText().trim() + str);if(tf.getText().equals("0")){tf.setText("0");IfResult = true;flag = true;}}}}/***小数点的事件监听*/class Dot implements ActionListener{public void actionPerformed(ActionEvent e) { IfResult = false;if(tf.getText().trim().indexOf(".") == -1){ tf.setText(tf.getText() + ".");}}}/***main方法*/public static void main(String[] args) { new Calucator().setVisible(true);}}。

相关文档
最新文档