科学计算器程序Java代码
- 格式:docx
- 大小:1.49 MB
- 文档页数:33
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){} }。
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开发一个功能强大的科学计算器。
一、需求分析1.支持基本的四则运算(加、减、乘、除)2.支持高级的数学函数(三角函数、指数函数、对数函数等)3.支持科学计数法(输入和显示均支持科学计数法)4.支持清空功能,删除单个字符功能5.支持键盘输入和界面按钮输入两种方式输入计算表达式二、界面设计1. 界面采用图形用户界面(GUI)设计,使用Swing或JavaFX等界面库进行开发2.使用文本框显示计算结果和表达式3.使用按钮实现数字和运算符的输入4.添加清空按钮和删除按钮5.添加科学计数法开关按钮三、代码实现1. 创建一个继承自JFrame的主窗口类,设置窗口标题、大小和关闭方式```public class ScientificCalculator extends JFrameprivate JTextField outputField;//其他界面组件声明public ScientificCalculatosuper("科学计算器");setSize(400, 600);setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//初始化界面组件并添加到窗口//...setVisible(true);}```2. 创建一个继承自JPanel的面板类,用于放置计算器的按钮和文本框```public class CalculatorPanel extends JPanelprivate JTextField outputField;//其他按钮和变量声明public CalculatorPanesetLayout(new BorderLayout();//初始化界面组件并添加到面板//...}```3.在面板类中添加按钮事件监听器,实现按钮的点击响应```public class CalculatorPanel extends JPanel implements ActionListenerprivate JTextField outputField;private JButton[] numberButtons;private JButton[] operatorButtons;//其他按钮和变量声明public CalculatorPanesetLayout(new BorderLayout();//初始化界面组件并添加到面板//...//添加按钮事件监听器for (JButton button : numberButtons)button.addActionListener(this);}for (JButton button : operatorButtons)button.addActionListener(this);}//其他按钮添加监听器//设置文本框只读outputField.setEditable(false);}public void actionPerformed(ActionEvent e)//根据按钮的命令执行相应的操作//...}```4.在按钮事件监听器中实现计算逻辑,调用数学库中的函数完成计算```public void actionPerformed(ActionEvent e)//清空操作outputField.setText("");//删除操作String currentText = outputField.getText(;outputField.setText(currentText.substring(0,currentText.length( - 1));} else//数字或运算符输入}```5.在启动类中创建主窗口对象,并将面板对象添加到主窗口中```public class Mainpublic static void main(String[] args)SwingUtilities.invokeLater(( ->ScientificCalculator calculator = new ScientificCalculator(;calculator.add(new CalculatorPanel();});}```四、测试与优化在开发完成后,需要对科学计算器进行测试,保证其功能正常,并进行优化,确保使用体验良好,例如添加键盘监听器,支持键盘输入,修复可能出现的Bug等。
java科学计算器(进制转换)JAVA综合程序设计与分析一、题目:用java语言编写科学计算器,要求完成加、减、乘、除以及基本函数处理还有数的进制转换。
二、摘要:本计算器可以进行简单的四则运算(加、减、乘、除)但仅限于十进制下,还可以进行(二进制,八进制,十进制)之间的相互转换,还有基本三角函数和平方根,对数等基本数学函数运算三、功能说明:A.运用两个面板的叠加做出界面。
B.通过在按钮的单击事件处理方法中调用类的成员方法calculate ()来进行简易计算器的各种运算,并正确实现运算功能。
C.调用Math包中的方法实现各函数功能。
D.添加菜单条,列出‘选项’、‘进制转换’、‘帮助’等菜单选项,并分别实现‘选项’中‘退出’的功能,通过调用Integer包中的方法实现二进制、八进制的转换,‘帮助'菜单栏中‘用法’的提示对话框。
E.整个程序对话框可实现最小化、最大化、关闭。
四、详细设计package计算器;import java.awt.*;import java.awt.event.*;import javax.swing.*;public class Calculator extends Frame implements ActionListener, WindowListener{privateprivateprivate 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 JButtonbutton_sqrt,button_plusminus,button_CE,button_cancel,butt on_1,button_ 2,button_3,button_4,button_5,button_6,button_7,button_8,but ton_9,button _0,button_plus,button_minus,button_multiply,button_divide,bu tton_point,button_equal,button_log,button_tan,button_cos,button_sin,butt on_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(butto n_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(but ton_plusm inus)||e.getSource().equals(button_cancel)||e.getSource().equals(b utton_CE)) { //非运算符的处理方法String input=e.getActionCommand();if (start){displayField.setText("");start=false;if(input.equals("+/-"))displayField.setText(displayField.getT ext()+"-");}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.getT ext()+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.setT ext("sqrt,exp等键是先输运算符再输数字\");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.界面2.基本运算,如54 -12 =42:3.数学函数运算,如9的开平方为3:六、总结与体会总结:(1)通过编写这个相对复杂的程序,让我认识解决实际问题前应现建立模型,再通过建立的模型使问题简单化,从而解决问题。
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代码例子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实现一个简单的学生信息管理系统,可以添加、删除、修改、查询学生信息。
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();}}。
//定义计算的类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;} }。
package calculator;import java.awt.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.math.BigDecimal;import javax.swing.*;public class Operation extends JFrame implements ActionListener{/****/private static final long serialVersionUID = 1L;private final String str[] = {"7","8","9","/","4","5","6","*","1","2", "3","-",".","0","=","+"};private final JButton[] JB = new JButton[str.length];private final JButton reset = new JButton("CE");private final JTextField display = new JTextField("");Operation(){super("计算器");JPanel panel1 = new JPanel(new BorderLayout());JPanel panel2 = new JPanel(new GridLayout(4,4));panel1.add(BorderLayout.CENTER, display);panel1.add(BorderLayout.EAST, reset);int i;for( i = 0;i < str.length;i++){JB[i] = new JButton(str[i]);panel2.add(JB[i]);}getContentPane().setLayout(new BorderLayout());getContentPane().add(BorderLayout.NORTH,panel1);getContentPane().add(BorderLayout.SOUTH, panel2);setSize(800,800);for(i = 0;i < str.length;i++){JB[i].addActionListener(this);}reset.addActionListener(this);display.addActionListener(this);setVisible(true);setDefaultCloseOperation((WindowConstants.DISPOSE_ON_CLOSE));pack();}public void actionPerformed(ActionEvent e) {// TODO 自动生成的方法存根Object target = e.getSource();String label = e.getActionCommand();if(target == reset){handlereset();}else if("0123456789.".indexOf(label)>=0){handleNumber(label);}elsehandleOperator(label);}private void handleNumber(String key) {// TODO 自动生成的方法存根if ((isFirstDigit)&&("0123456789".indexOf(key)>=0))display.setText(key);else if ((key.equals(".")))display.setText(display.getText() + ".");else if (!key.equals("."))display.setText(display.getText() + key);isFirstDigit = false;}boolean isFirstDigit = true;double number1 = 0.0;double number2 = 0.0;String operator = "=";BigDecimal df ;private void handlereset() {// TODO 自动生成的方法存根display.setText("");isFirstDigit = true;operator = "=";}public void handleOperator(String key) {if (operator.equals("+")){number1 = Double.valueOf(display.getText());number2 = add(number1,number2);df = new BigDecimal(number2);display.setText(String.valueOf( df.setScale(5, BigDecimal.ROUND_HALF_UP).doubleValue()));}else if (operator.equals("-")){number1 = Double.valueOf(display.getText());number2 = sub(number2,number1);df = new BigDecimal(number2);display.setText(String.valueOf( df.setScale(5, BigDecimal.ROUND_HALF_UP).doubleValue()));}else if (operator.equals("*")){number1 = Double.valueOf(display.getText());number2 = mul(number1,number2);df = new BigDecimal(number2);display.setText(String.valueOf( df.setScale(5, BigDecimal.ROUND_HALF_UP).doubleValue()));}else if (operator.equals("/")){number1 = Double.valueOf(display.getText());if(number1 == 0)display.setText("error");else{number2 = div(number2,number1);df = new BigDecimal(number2);display.setText(String.valueOf( df.setScale(5, BigDecimal.ROUND_HALF_UP).doubleValue()));}}else if (operator.equals("=")){number2 = Double.valueOf(display.getText());display.setText(String.valueOf(number2));}operator = key;isFirstDigit = true;}private double div(double key1, double key2) {// TODO 自动生成的方法存根double result = 0.0;result = key1 / key2;return result;}private double mul(double key1, double key2) {// TODO 自动生成的方法存根double result = 0.0;result = key1 * key2;return result;}private double sub(double key1, double key2) { // TODO 自动生成的方法存根double result = 0.0;result = key1 - key2;return result;}private double add(double key1, double key2) { // TODO 自动生成的方法存根double result = 0.0;result = number1 + number2;return result;}public static void main(String[] args) {new Operation();}}。
import java.awt.*;import java.awt.event.*;import javax.swing.*;public class Ca extends JFrame implements ActionListener{//*********************************************************************** //标准型计算器控件键钮static JFrame f1 = new JFrame("计算器");private String KEYS[] = {"7","8","9","/","sqrt","4","5","6","*","%","1","2","3","-","1/x","0","+/-",".","+","="};private String M[] = {" ","MC","MR","MS","M+"};private String COM[] = {"Backspace","CE","C"};private JButton keys[] = new JButton[KEYS.length];private JButton com[] = new JButton[COM.length];private JButton m[] = new JButton[M.length];private JTextField result,hh,jj;MenuBar menubar1=new MenuBar();Menu edit=new Menu("编辑(E)"),view=new Menu("查看(V)"),help=new Menu("帮助(H)");MenuItem copy=new MenuItem("复制(C)"),paste=new MenuItem("粘贴(P)"),standar=new MenuItem("标准型(T)"),science=new MenuItem("科学型(S)"),numgroup=new MenuItem("数字分组(I)"),helpt=new MenuItem("帮助主题(H)"),about=new MenuItem("关于计算器(A)");private boolean firstDigit = true; //判断第一个输入的字符是否是数字private double resultNum = 0.0,resultNum2 = 0.0; //中间结果private String operator = "=",co,str,operator2 = "=";private boolean operateValidFlag = true;//*********************************************************************** //科学性计算器控件及按钮static JFrame f2 = new JFrame("科学计算器");private JTextField result2;private String[] KON = {"sta","F-E","(",")","MC","Ave","dms","Exp","In","MR","Sum","sin","x^y","log","MS","s","cos","x^3","n!","M+","Dat","tan","x^2","1/x","pi"};private String[] KO = {"7","8","9","/","Mod","And","4","5","6","*","Or","Xor","1","2","3","-","Lsh","Not","0","+/-",".","+","=","Int","A","B","C","D","E","F"};private String ITM[]={"标准型","科学型","十六进制数(H) F5","十进制(D) F6","八进制(O) F7","二进制(B) F8","四字(Q) F12","DWORD 值(R)F2","单字(W)F3","字节(Y) F4","数字分组(I)"};private final String[] COMM = {"Backspace","CE","C"};private JButton comm[] = new JButton[COMM.length];private JButton kon[] = new JButton[KON.length];private JButton ko[] = new JButton[KO.length];private MenuItem itm[] = new MenuItem[ITM.length];private JPanel panel0,panel1,panel2,panel3,panel4,panel5,panel6;Checkbox checkbox1,checkbox2,checkbox3,checkbox4;MenuBar menubar2=new MenuBar(); //添加菜单条Menu edit2=new Menu("编辑(E)"),view2=new Menu("查看(V)"),help2=new Menu("帮助(H)");MenuItem copy2=new MenuItem("复制(C) Ctrl+C"),past2=new MenuItem("粘贴(P) Ctrl+V"),standar2=new MenuItem("标准型(T)"),science2=new MenuItem("科学型(S)"),numgroup2=new MenuItem("数字分组(I)"),menuitem1=new MenuItem("十六进制数(H) F5"),menuitem2=new MenuItem("十进制(D) F6"),menuitem3=new MenuItem("八进制(O) F7"),menuitem4=new MenuItem("二进制(B) F8"),menuitem5=new MenuItem("四字(Q) F12"),menuitem6=new MenuItem("DWORD 值(R)F2"),menuitem7=new MenuItem("单字(W)F3"),menuitem8=new MenuItem("字节(Y) F4"),helpt2=new MenuItem("帮助主题(H)"),about2=new MenuItem("关于计算器(A)");//*********************************************************************** //构造函数public Ca(){//标准型开始初始化********************result = new JTextField("0.");result.setHorizontalAlignment(JTextField.RIGHT); //文字右对齐result.setEditable(false); //设置为不可编辑result.setBackground(Color.WHITE); //设置颜色为白色JPanel k0 = new JPanel();k0.setLayout(new GridLayout(4,5,5,5));for(int i = 0;i < KEYS.length;i++){keys[i] = new JButton(KEYS[i]);k0.add(keys[i]);keys[i].setForeground(Color.blue);}keys[3].setForeground(Color.red);keys[8].setForeground(Color.red);keys[13].setForeground(Color.red);keys[18].setForeground(Color.red);keys[19].setForeground(Color.red);JPanel c0 = new JPanel();c0.setLayout(new GridLayout(1,3,5,5));for(int i = 0;i < COM.length;i++){com[i] = new JButton(COM[i]);c0.add(com[i]);com[i].setForeground(Color.red);}JPanel m0 = new JPanel();m0.setLayout(new GridLayout(5,1,5,5));for(int i = 0;i < M.length;i++){m[i] = new JButton(M[i]);m0.add(m[i]);m[i].setForeground(Color.red);}m[0].setForeground(Color.black);//f1的监视器for(int i = 0;i < KEYS.length;i++){keys[i].addActionListener(this);}for(int i = 0;i < COM.length;i++){com[i].addActionListener(this);}for(int i = 0;i < M.length;i++){m[i].addActionListener(this);}//复制事件copy.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){int count;count=str.length();if(count!=0)co=result.getText();elseSystem.out.println("没有可复制的对象");}});//粘贴事件paste.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){str=co;result.setText(str);}});//复制事件copy2.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){int count;count=str.length();if(count!=0)co=result2.getText();elseSystem.out.println("没有可复制的对象");}});//粘贴事件past2.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){str=co;result2.setText(str);}});edit.add(copy);edit.add(paste);view.add(standar);view.add(science);view.addSeparator();view.add(numgroup);help.add(helpt);help.addSeparator();help.add(about);menubar1.add(edit);menubar1.add(view);menubar1.add(help);//整体布局JPanel p1 = new JPanel();p1.setLayout(new BorderLayout());p1.add("North",c0);p1.add("Center",k0);JPanel p2 = new JPanel();p2.setLayout(new BorderLayout());p2.add("Center",result);f1.setLayout(new BorderLayout(3,5));f1.add("North",p2);f1.add("Center",p1);f1.add("West",m0);f1.setBackground(Color.LIGHT_GRAY);f1.setLocation(200,200);f1.setMenuBar(menubar1);f1.setVisible(true);f1.setResizable(false);//不可最大化f1.pack(); //紧凑f1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//标准型初始化结束//**************************************************** standar2.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){f1.setVisible(true);f2.setVisible(false); //按钮不可操作}});science.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){f1.setVisible(false);f2.setVisible(true); //按钮不可操作}});//****************************************************//科学性初始化开始panel0=new JPanel();panel1=new JPanel();panel2=new JPanel();panel3=new JPanel();panel4=new JPanel();panel5=new JPanel();panel6=new JPanel();panel0.setLayout(new GridLayout(1,4)); //设置网格型布局管理器panel1.setLayout(new GridLayout(1,3,30,0));panel2.setLayout(new GridLayout(1,2));panel3.setLayout(new GridLayout(1,3,5,0));panel4.setLayout(new GridLayout(5,5,5,5));panel5.setLayout(new GridLayout(5,6,5,5));panel6.setLayout(new FlowLayout(FlowLayout.LEFT)); //按钮左对齐result2 = new JTextField("0.",100);result2.setHorizontalAlignment(JTextField.RIGHT); //文字右对齐result2.setEditable(false); //设置为文本不可编辑result2.setBackground(Color.WHITE); //设置文本框颜色为白色CheckboxGroup cbg1=new CheckboxGroup();checkbox1=new Checkbox("十六进制",false,cbg1);checkbox2=new Checkbox("十进制",true,cbg1);checkbox3=new Checkbox("八进制",false,cbg1);checkbox4=new Checkbox("二进制",false,cbg1);panel0.add(checkbox1);panel0.add(checkbox2);panel0.add(checkbox3);panel0.add(checkbox4);CheckboxGroup cbg2=new CheckboxGroup();panel1.add(new Checkbox("角度",true,cbg2));panel1.add(new Checkbox("弧度",false,cbg2));panel1.add(new Checkbox("梯度",false,cbg2));JLabel HH = new JLabel(" ");panel2.add(new Checkbox("Inv",false));panel2.add(new Checkbox("Hyp",false));hh = new JTextField();jj = new JTextField();hh.setText(" ");hh.setEditable(false);jj.setText(" ");jj.setEditable(false);panel2.add(hh);panel2.add(HH);panel2.add(jj);panel6.add(result2);edit2.add(copy2);edit2.add(past2);view2.add(standar2);view2.add(science2);view2.addSeparator();view2.add(menuitem1);view2.add(menuitem2);view2.add(menuitem3);view2.add(menuitem4);view2.addSeparator();view2.add(menuitem5);view2.add(menuitem6);view2.add(menuitem7);view2.add(menuitem8);view2.addSeparator();view2.add(numgroup2);help2.add(helpt2);help2.addSeparator();help2.add(about2);menubar2.add(edit2);menubar2.add(view2);menubar2.add(help2);for(int i = 0;i < COMM.length;i++){comm[i] = new JButton(COMM[i]);panel3.add(comm[i]);comm[i].setForeground(Color.red); }for(int i = 0;i < KON.length;i++){kon[i] = new JButton(KON[i]);panel4.add(kon[i]);kon[i].setForeground(Color.magenta); }kon[4].setForeground(Color.red);kon[9].setForeground(Color.red);kon[14].setForeground(Color.red);kon[19].setForeground(Color.red);kon[0].setForeground(Color.blue);kon[24].setForeground(Color.blue);kon[5].setForeground(Color.blue);kon[10].setForeground(Color.blue);kon[15].setForeground(Color.blue);kon[20].setForeground(Color.blue);for(int i = 0;i < KO.length;i++){ko[i] = new JButton(KO[i]);panel5.add(ko[i]);ko[i].setForeground(Color.red);}ko[0].setForeground(Color.blue);ko[1].setForeground(Color.blue);ko[2].setForeground(Color.blue);ko[6].setForeground(Color.blue);ko[7].setForeground(Color.blue);ko[8].setForeground(Color.blue);ko[12].setForeground(Color.blue);ko[13].setForeground(Color.blue);ko[14].setForeground(Color.blue);ko[18].setForeground(Color.blue);ko[19].setForeground(Color.blue);ko[20].setForeground(Color.blue);//添加监视器for(int i = 0;i < KON.length;i++){kon[i].addActionListener(new ca2Actionlistener()); }for(int i = 0;i < KO.length;i++){ko[i].addActionListener(new ca2Actionlistener());}for(int i = 0;i < COMM.length;i++){comm[i].addActionListener(new ca2Actionlistener()); }checkbox1.addItemListener(new itemListener()); checkbox2.addItemListener(new itemListener()); checkbox3.addItemListener(new itemListener()); checkbox4.addItemListener(new itemListener());JPanel pp1 = new JPanel();pp1.setLayout(new GridLayout(3,1));pp1.add(panel6);JPanel pp2 = new JPanel();pp2.setLayout(new FlowLayout(FlowLayout.LEFT));pp2.add(panel0);pp2.add(new JLabel(" "));pp2.add(panel1);pp1.add(pp2);JPanel pp3 = new JPanel();pp3.setLayout(new FlowLayout(FlowLayout.LEFT));pp3.add(panel2);pp3.add(new JLabel(" "));pp3.add(panel3);pp1.add(pp3);JPanel pp4 = new JPanel();pp4.setLayout(new FlowLayout(FlowLayout.LEFT));JLabel NN = new JLabel(" ");f2.setLayout(new GridLayout(2,1));f2.add(pp1);pp4.add(panel4);pp4.add(NN);pp4.add(panel5);f2.add(pp4);f2.setBackground(Color.LIGHT_GRAY);f2.setSize(655,340);f2.setLocation(200,200);f2.setMenuBar(menubar2);f2.setVisible(false);f2.setResizable(false);f2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);}//科学型初始化结束//****************************************************//标准型监听器public void actionPerformed(ActionEvent e){String label = e.getActionCommand();//获取事件源的标签if(label.equals(COM[0]))//按BackspacehandleBS();else if(label.equals(COM[1]))//按CEresult.setText("0");else if(label.equals(COM[2]))//按ChandleC();else if(label.equals(M[1]))//按MChandleMC();else if(label.equals(M[2]))//按MRhandleMR();else if(label.equals(M[3]))//按MShandleMS();else if(label.equals(M[4]))//按M+handleM();else if("0123456789.".indexOf(label) >= 0)//按数字键或者小数点handleNB(label);else//按运算符handleOR(label);}private void handleBS()//处理Backspace{String text = new String(result.getText());int j = text.length();if(j > 0){text = text.substring(0,j - 1);if(text.length() == 0){result.setText("0");firstDigit = true;operator = "=";}else{result.setText(text);}}}private void handleNB(String key)//处理数字键{if(firstDigit){result.setText(key);}else if((key.equals("."))&&(result.getText().indexOf(".")<0)){result.setText(result.getText() + ".");}else if(!key.equals(".")){result.setText(result.getText() + key);}firstDigit = false;}private void handleC()//处理C{result.setText("0");firstDigit = true;operator = "=";}private void handleOR(String key)//处理运算符{if(operator.equals("/")){if(getNumberFromText() == 0.0){operateValidFlag = false;result.setText("除数不能是零");}elseresultNum /= getNumberFromText();}else if(operator.equals("1/x")){if(resultNum == 0.0){operateValidFlag = false;result.setText("零没有倒数");}elseresultNum = 1 / resultNum;}else if(operator.equals("+"))resultNum += getNumberFromText();else if(operator.equals("-"))resultNum -= getNumberFromText();else if(operator.equals("*"))resultNum *= getNumberFromText();else if(operator.equals("sqrt"))resultNum = Math.sqrt(resultNum);///////// else if(operator.equals("%"))resultNum = resultNum / 100;else if(operator.equals("+/-"))resultNum = resultNum * (-1);else if(operator.equals("=")){ resultNum = getNumberFromText();}if(operateValidFlag)// 双精度浮点数的运算{long t1;double t2;t1 = (long) resultNum;t2 = resultNum - t1;if(t2 == 0 ){result.setText(String.valueOf(t1));}else{result.setText(String.valueOf(resultNum));}}//运算符等于用户按的按钮operator = key;firstDigit = true;operateValidFlag = true;}public void handleMC()//处理MC,清除内存{resultNum = 0.0;result.setText("0");m[0].setText(" ");firstDigit = true;operator = "=";}public void handleMR()//处理MR,重新调用存储的数据{if(result.getText() != "" )//有记忆数字{result.setText("" + resultNum);}}public void handleMS()//处理MS,存储显示的数据{resultNum = Double.valueOf(result.getText()).doubleValue();m[0].setText("M");result.setText("0");firstDigit = true;operator = "=";}public void handleM()//处理M+,将显示的数字与已经存储的数据相加要查看新的数字单击MR{resultNum = resultNum + Double.valueOf(result.getText()).doubleValue();}//标准型监听器定义部分结束//****************************************************//科学性监听器定义class itemListener implements ItemListener{public void itemStateChanged(ItemEvent e){Checkbox cb=(Checkbox)e.getItemSelectable(); //获取事件源的resetable(); //使按钮重新可用if(cb.getLabel().equals( "十六进制")){kon[1].setEnabled(false);kon[5].setEnabled(false);kon[6].setEnabled(false);kon[7].setEnabled(false);kon[10].setEnabled(false);kon[11].setEnabled(false);kon[15].setEnabled(false);kon[16].setEnabled(false);kon[20].setEnabled(false);kon[21].setEnabled(false);kon[24].setEnabled(false);kon[1].setForeground(Color.gray);kon[5].setForeground(Color.gray);kon[6].setForeground(Color.gray);kon[7].setForeground(Color.gray);kon[10].setForeground(Color.gray);kon[11].setForeground(Color.gray);kon[15].setForeground(Color.gray);kon[16].setForeground(Color.gray);kon[20].setForeground(Color.gray);kon[21].setForeground(Color.gray);ko[1].setForeground(Color.blue);ko[2].setForeground(Color.blue);ko[24].setForeground(Color.blue);ko[25].setForeground(Color.blue);ko[26].setForeground(Color.blue);ko[27].setForeground(Color.blue);ko[28].setForeground(Color.blue);ko[29].setForeground(Color.blue);ko[0].setForeground(Color.blue);ko[6].setForeground(Color.blue);ko[7].setForeground(Color.blue);ko[8].setForeground(Color.blue);ko[13].setForeground(Color.blue);ko[14].setForeground(Color.blue); }else if(cb.getLabel().equals( "十进制")) {kon[5].setEnabled(false);kon[10].setEnabled(false);kon[15].setEnabled(false);kon[20].setEnabled(false);ko[24].setEnabled(false);ko[25].setEnabled(false);ko[26].setEnabled(false);ko[27].setEnabled(false);ko[28].setEnabled(false);ko[29].setEnabled(false);kon[5].setForeground(Color.gray); kon[10].setForeground(Color.gray); kon[15].setForeground(Color.gray); kon[20].setForeground(Color.gray); ko[24].setForeground(Color.gray);ko[25].setForeground(Color.gray);ko[26].setForeground(Color.gray);ko[27].setForeground(Color.gray);ko[28].setForeground(Color.gray);ko[29].setForeground(Color.gray);ko[1].setForeground(Color.blue);ko[2].setForeground(Color.blue);kon[1].setForeground(Color.magenta);kon[7].setForeground(Color.magenta); kon[11].setForeground(Color.magenta); kon[16].setForeground(Color.magenta); kon[21].setForeground(Color.magenta); kon[24].setForeground(Color.blue);ko[0].setForeground(Color.blue);ko[6].setForeground(Color.blue);ko[7].setForeground(Color.blue);ko[8].setForeground(Color.blue);ko[13].setForeground(Color.blue);ko[14].setForeground(Color.blue);}else if(cb.getLabel().equals( "八进制")) {kon[1].setEnabled(false);kon[5].setEnabled(false);kon[6].setEnabled(false);kon[7].setEnabled(false);kon[10].setEnabled(false);kon[11].setEnabled(false);kon[15].setEnabled(false);kon[16].setEnabled(false);kon[20].setEnabled(false);kon[21].setEnabled(false);kon[24].setEnabled(false);ko[1].setEnabled(false);ko[2].setEnabled(false);ko[24].setEnabled(false);ko[25].setEnabled(false);ko[26].setEnabled(false);ko[27].setEnabled(false);ko[28].setEnabled(false);ko[29].setEnabled(false);kon[1].setForeground(Color.gray);kon[5].setForeground(Color.gray);kon[6].setForeground(Color.gray);kon[7].setForeground(Color.gray);kon[10].setForeground(Color.gray);kon[11].setForeground(Color.gray);kon[15].setForeground(Color.gray);kon[16].setForeground(Color.gray);kon[20].setForeground(Color.gray);kon[24].setForeground(Color.gray);ko[1].setForeground(Color.gray);ko[2].setForeground(Color.gray);ko[24].setForeground(Color.gray);ko[25].setForeground(Color.gray);ko[26].setForeground(Color.gray);ko[27].setForeground(Color.gray);ko[28].setForeground(Color.gray);ko[29].setForeground(Color.gray);ko[0].setForeground(Color.blue);ko[6].setForeground(Color.blue);ko[7].setForeground(Color.blue);ko[8].setForeground(Color.blue);ko[13].setForeground(Color.blue);ko[14].setForeground(Color.blue); }else if(cb.getLabel().equals( "二进制")) {kon[1].setEnabled(false);kon[5].setEnabled(false);kon[6].setEnabled(false);kon[7].setEnabled(false);kon[10].setEnabled(false);kon[11].setEnabled(false);kon[15].setEnabled(false);kon[16].setEnabled(false);kon[20].setEnabled(false);kon[21].setEnabled(false);kon[24].setEnabled(false);ko[1].setEnabled(false);ko[2].setEnabled(false);ko[24].setEnabled(false);ko[25].setEnabled(false);ko[26].setEnabled(false);ko[27].setEnabled(false);ko[28].setEnabled(false);ko[29].setEnabled(false);ko[0].setEnabled(false);ko[6].setEnabled(false);ko[7].setEnabled(false);ko[8].setEnabled(false);ko[13].setEnabled(false);ko[14].setEnabled(false);kon[1].setForeground(Color.gray);kon[5].setForeground(Color.gray);kon[6].setForeground(Color.gray);kon[7].setForeground(Color.gray);kon[10].setForeground(Color.gray);kon[11].setForeground(Color.gray);kon[15].setForeground(Color.gray);kon[16].setForeground(Color.gray);kon[20].setForeground(Color.gray);kon[21].setForeground(Color.gray);kon[24].setForeground(Color.gray);ko[1].setForeground(Color.gray);ko[2].setForeground(Color.gray);ko[24].setForeground(Color.gray);ko[25].setForeground(Color.gray);ko[26].setForeground(Color.gray);ko[27].setForeground(Color.gray);ko[28].setForeground(Color.gray);ko[29].setForeground(Color.gray);ko[0].setForeground(Color.gray);ko[6].setForeground(Color.gray);ko[7].setForeground(Color.gray);ko[8].setForeground(Color.gray);ko[13].setForeground(Color.gray);ko[14].setForeground(Color.gray);}}}class ca2Actionlistener implements ActionListener{public void actionPerformed(ActionEvent e){String label2 = e.getActionCommand();//获取事件源的标签if(label2.equals(COMM[0]))//按BackspacehandleBS2();else if(label2.equals(COMM[1]))//按CEresult2.setText("0");else if(label2.equals(COMM[2]))//按ChandleC2();else if(label2.equals(KON[4]))//按MChandleMC2();else if(label2.equals(KON[9]))//按MRhandleMR2();else if(label2.equals(KON[14]))//按MShandleMS2();else if(label2.equals(KON[19]))//按M+handleM2();else if(label2.equals(KON[11]))//按sinhandleSI();else if(label2.equals(KON[12])) //按x^yhandleYT();else if(label2.equals(KON[13])) //按loghandleLO();else if(label2.equals(KON[16])) //按coshandleCO();else if(label2.equals(KON[17])) //按x^3handleTT();else if(label2.equals(KON[22])) //按x^2handlePF();else if(label2.equals(KON[18])) //按n!handleJC();else if(label2.equals(KON[21])) //按tanhandleTA();else if(label2.equals(KON[24]))//按piresult2.setText(""+3.141592653);else if("0123456789.".indexOf(label2) >= 0)//按数字键或者小数点handleNB2(label2);else//按运算符handleOR2(label2);}}//科学性监听器定义结束//****************************************************//科学性计算器用到的函数void resetable() //使按钮重新可用{for(int i=0;i<KON.length;i++)kon[i].setEnabled(true);for(int i=0;i<KO.length;i++)ko[i].setEnabled(true);}private void handleC2()//处理C{result2.setText("0");firstDigit = true;operator2 = "=";}private void handleBS2()//处理Backspace{String text2 = new String(result2.getText());int j2 = text2.length();if(j2>0){text2 = text2.substring(0,j2 - 1);if(text2.length() == 0){result2.setText("0");firstDigit = true;operator2 = "=";}else{result2.setText(text2);}}}public void handleMC2()//处理MC,清除内存{resultNum2 = 0.0;result2.setText("0");jj.setText(" ");firstDigit = true;operator2 = "=";}private void handleNB2(String key)//处理数字键{if(firstDigit){result2.setText(key);}else if((key.equals("."))&&(result2.getText().indexOf(".")<0)){result2.setText(result2.getText() + ".");}else if(!key.equals(".")){result2.setText(result2.getText() + key);}firstDigit = false;}public void handleMR2()//处理MR,重新调用存储的数据{if(result2.getText() != "" )//有记忆数字result2.setText("" + resultNum2);}public void handleMS2()//处理MS,存储显示的数据{resultNum2 = Double.valueOf(result2.getText()).doubleValue();result2.setText("0");jj.setText("M");firstDigit = true;operator2 = "=";}public void handleM2()//处理M+,将显示的数字与已经存储的数据相加要查看新的数字单击MR{resultNum2 = resultNum2 + Double.valueOf(result2.getText()).doubleValue();}public void handleSI()//sin{double i= getNumberFromText2();result2.setText(String.valueOf(Math.sin(i)));}public void handleYT()//Y次方{if(getNumberFromText2() == 0.0||getNumberFromText2() == 1){resultNum2 = getNumberFromText2();}else{for(int i=1;i<=getNumberFromText2();i++){resultNum2 *=resultNum2;}}result2.setText(String.valueOf(resultNum2));}public void handleLO()//对数{double i= getNumberFromText2();resultNum2 =Math.log(i);result2.setText(String.valueOf(resultNum2));}public void handleCO()//cos{double i= getNumberFromText2();resultNum2 =Math.cos(i);result2.setText(String.valueOf(resultNum2));}public void handleTT()//三次方{if(getNumberFromText2() == 0.0||getNumberFromText2() == 1){resultNum2= getNumberFromText2();}else{resultNum2= getNumberFromText2()*getNumberFromText2()*getNumberFromText2();}result2.setText(String.valueOf(resultNum2));}public void handlePF()//平方{if(getNumberFromText2() == 0.0||getNumberFromText2() == 1){resultNum2 = getNumberFromText2();}else{resultNum2 = getNumberFromText2()*getNumberFromText2();}result2.setText(String.valueOf(resultNum2));}public void handleJC()//阶乘{double i = getNumberFromText2();if((i%2==0)||(i%2==1))//判断为整数放进行阶乘操作{int j = (int)i;//强制类型转换int resultNum2=1;for(int k=1;k<=j;k++)resultNum2 *= k;result2.setText(String.valueOf(resultNum2));}else{result2.setText("无法求阶乘");}}public void handleTA()//tan{double i= getNumberFromText2();resultNum2 =Math.tan(i);result2.setText(String.valueOf(resultNum2));}private void handleOR2(String key)//处理运算符{if(operator2.equals("/")){if(getNumberFromText2() == 0.0){operateValidFlag = false;result2.setText("除数不能是零");}elseresultNum2 /= getNumberFromText2();}else if(operator2.equals("1/x")){if(resultNum2 == 0.0){operateValidFlag = false;result2.setText("零没有倒数");}elseresultNum2 = 1 / resultNum2;}else if(operator2.equals("+"))resultNum2 += getNumberFromText2();else if(operator2.equals("-"))resultNum2 -= getNumberFromText2();else if(operator2.equals("*"))resultNum2 *= getNumberFromText2();else if(operator2.equals("sqrt"))resultNum2 = Math.sqrt(resultNum2);/////////else if(operator2.equals("%"))resultNum2 = resultNum2 / 100;else if(operator2.equals("+/-"))resultNum2 = resultNum2 * (-1);else if(operator2.equals("=")){ resultNum2 = getNumberFromText2();}if(operateValidFlag)// 双精度浮点数的运算{long t1;double t2;t1 = (long) resultNum2;t2 = resultNum2 - t1;if(t2 == 0 ){result2.setText(String.valueOf(t1));}else{result2.setText(String.valueOf(resultNum2));}}//运算符等于用户按的按钮operator2 = key;firstDigit = true;operateValidFlag = true;}//**************************************************** private double getNumberFromText2()/*从结果文本框中获取数字*/{double res2 = 0;try{。
北邮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的结果上处理。
计算器源代码一、计算器源代码文件名: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);}}二、计算器界面三、修改后计算器界面。
科学计算器源代码以下是一个简单的科学计算器的源代码,包含了基本的数学运算、三角函数、指数和对数运算、阶乘和组合运算等功能。
```#include <iostream>#include <cmath>using namespace std;//计算器类class ScientificCalculatorpublic://基本运算double add(double a, double b)return a + b;}double subtract(double a, double b)return a - b;}double multiply(double a, double b)return a * b;}double divide(double a, double b)if (b != 0)return a / b;} elsecout << "Error: Division by zero!" << endl; return 0;}}//三角函数运算double sine(double angle)return sin(angle);}double cosine(double angle)return cos(angle);}double tangent(double angle)return tan(angle);}//指数和对数运算double exponent(double x) return exp(x);}double logarithm(double x) return log10(x);}//阶乘运算double factorial(int n)if (n == 0)return 1;} elseint result = 1;for (int i = 1; i <= n; i++) result *= i;}return result;}}//组合运算if (n >= r)return factorial(n) / (factorial(r) * factorial(n - r));} elsecout << "Error: Invalid input!" << endl;return 0;}}};//主函数int maiScientificCalculator calculator;//进行一些简单的计算cout << "Addition: " << calculator.add(5, 3) << endl;cout << "Subtraction: " << calculator.subtract(5, 3) << endl;cout << "Multiplication: " << calculator.multiply(5, 3) << endl;cout << "Division: " << calculator.divide(5, 3) << endl;//三角函数运算cout << "Sine: " << calculator.sine(0.5) << endl;cout << "Cosine: " << calculator.cosine(0.5) << endl;cout << "Tangent: " << calculator.tangent(0.5) << endl;//指数和对数运算cout << "Exponent: " << calculator.exponent(2) << endl;cout << "Logarithm: " << calculator.logarithm(100) << endl;//阶乘和组合运算cout << "Factorial: " << calculator.factorial(5) << endl;return 0;```这个科学计算器的源代码使用了面向对象的编程思想,将不同的数学运算封装成类的成员函数。
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代码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);}}。