用java编写简单计算器

合集下载

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

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

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

java计算器程序代码

java计算器程序代码

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

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

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

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

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

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

java实验报告——简单计算器的编写五篇范文

java实验报告——简单计算器的编写五篇范文

java实验报告——简单计算器的编写五篇范文第一篇:java实验报告——简单计算器的编写JAVA实验报告——简单计算器的编写班级:学号:姓名:一、实验目的1.掌握java图形用户界面(GUI)的设计原理和程序结构2.能设计复核问题要求的图形用户界面程序3.掌握常用组件的事件接口4.应用awt和swing组件进行应用程序设计二、实验条件1.计算机一台2.java软件开发环境三、实验步骤1、编写代码:mport java.awt.*;import java.awt.event.*;import javax.swing.*;public class JCalculator extends JFrame implements ActionListener {private static final long serialVersionUID =-***457Lprivate class WindowCloser extends WindowAdapter {public void windowClosing(WindowEvent we){System.exit(0);}}int i;private final String[] str = { “7”, “8”, “9”, “/”, “4”, “5”, “6”, “*”, “1”,“2”, “3”, “-”, “.”, “0”, “=”, “+” };JButton[] buttons = new JButton[str.length]; JButton reset = new JButton(“CE”); JTextField display = new JTextField(“0”);public JCalculator(){super(“Calculator”);JPanel panel1 = new JPanel(new GridLayout(4, 4)); for(i = 0;i < str.length;i++){buttons[i] = new JButton(str[i]);panel1.add(buttons[i]);}JPanel panel2 = new JPanel(new BorderLayout()); panel2.add(“Center”, display);panel2.add(“East”, reset);getContentPane().setLayout(new BorderLayout()); getContentPane().add(“North”, panel2); getContentPane().add(“Center”, panel1);for(i = 0;i < str.length;i++)buttons[i].addActionListener(this);reset.addActionListener(this);display.addActionListener(this); addWindowListener(new WindowCloser()); setSize(800, 800);setVisible(true);pack();}public void actionPerformed(ActionEvent e){ Object target = e.getSource();String label = e.getActionCommand();if(target == reset)handleReset();else if(“0123456789.”.indexOf(label)> 0)handleNumber(label);elsehandleOperator(label);}boolean isFirstDigit = true;public void handleNumber(String key){if(isFirstDigit)display.setText(key);else if((key.equals(“.”))&&(display.getText().indexOf(“.”)< 0))display.setText(display.getText()+ “.”);else if(!key.equals(“.”))display.setText(display.getText()+ key);isFirstDigit = false;}public void handleReset(){display.setText(“0”);isFirstDigit = true;operator = “=”;}double number = 0.0;String operator = “=”;public void handleOperator(String key){if(operator.equals(“+”))number += Double.valueOf(display.getText());else if(operator.equals(“-”))number-= Double.valueOf(display.getText());else if(operator.equals(“*”))number *= Double.valueOf(display.getText());else if(operator.equals(“/”))number /= Double.valueOf(display.getText());else if(operator.equals(“=”))number = Double.valueOf(display.getText());display.setText(String.valueOf(number));operator = key;isFirstDigit = true;}public static void main(String[] args){new JCalculator();} }2、运行结果,见截图计算测试:123+456=579结果正确,程序无误。

基于java的简易计算器的设计

基于java的简易计算器的设计

基于java的简易计算器的设计摘要自从java语言诞生以来,java语言就以不可抵挡的趋势很快成为国际上广泛流行的面向对象编程语言,它既具有高级语言的特点,又少了C语言中指针特点,因而变得简单了很多。

Java是一种可以撰写跨平台应用软件的面向对象的程序设计语言,其具有卓越的通用性、高效性、平台移植性和安全性,广泛应用于个人PC、数据中心、游戏控制台、科学超级计算机、移动电话和互联网,同时拥有全球最大的开发者专业社群。

在全球云计算和移动互联网的产业环境下,Java更具备了显著优势和广阔前景。

本文介绍了用java语言编写一个简易计算器。

实现数学上的加、减、乘、除、乘方、开方、阶乘、正弦、余弦运算等相关运算。

利用这个程序可以方便的进行日常性的小规模运算,小巧简易,是个实用的工具。

关键词:程序设计;简易计算器;java语言THE DESIGN OF SIMPLE CALCULATOR BASED ON JA V AABSTRACTSince the inception of the java language, java language Take irresistible trend soon beca me widespread international popular object-oriented programming language, both with advan ced language features, and less of the C language pointer characteristics, and thus becomes a l ot simpler . Java is a cross-platform application software can write object-oriented programmi ng language, which has excellent versatility, efficiency, platform portability, and security, are widely used in personal PC, data center, gaming consoles, scientific super-computers, mobile phones and the Internet, also has the world's largest developer of professional community. In t he global cloud computing and mobile Internet industry environment, Java and more have sig nificant advantages and broad prospects.This article describes the use java language a simple calculator. Achieve mathematical addition, subtraction, multiplication, division, involution, evolution, factorial, sine, cosine op erations and other related operations. With this program you can easily carry out daily operati ons of small-scale, small simple, is a useful tool.Key words:program design;simple calculator;java language目录1前言 (1)1.1 课程设计背景 (1)1.2 需求环境 (1)1.3 课程设计思路 (1)2课程设计概要 (2)3 计算器详细设计 (3)3.1 计算器界面……….………….........………………………………………. .33.1.1 CAL主类的显示分布 (3)3.1.2计算器显示界面实现代码 (3)3.2 监听各个按钮的类 (5)3.2.1 编写监听类目的 (5)3.2.2 监听类实现代码 (5)3.3 按键响应类 (7)3.3.1 响应类编写的目的 (7)3.2.2 响应类实现代码 (7)3.3 运算处理类 (9)3.3.1 处理方式 . (9)3.2.2 处理类实现代码 (9)4 运行与调试 (12)4.1 进入程序主界面 (12)4.2 加减乘除功能实现 (12)4.3 正余弦、正切功能实现 (13)4.4 阶乘功能实现 (13)4.5 乘方、开方功能实现 (14)5 实验总结 (15)参考文献 (16)附录:源代码 (17)1 前言1.1 课程设计背景日常生活中我们经常会遇到一些小型数据计算的问题,本课程设计就是以此为出发点,设计了这样一个简单的计算器,用以实现基本的数学运算。

java编写的简单计算器

java编写的简单计算器

import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JPanel;import javax.swing.JTextField;public class Calculator extends JFrame{private JPanel jp;private JTextField tAdd1,tAdd2,tAdd3,tSub1,tSub2,tSub3,tMul1,tMul2,tMul3,tDiv1,tDiv2,tDiv3;private JLabel tShow,label1,label2,label3,label4,label5,label6,label7,label8;private JButton result,exit;//构造器public Calculator(){super("简易计算器");Init();}//初始化public void Init(){ //显示区tShow=new JLabel(" 感谢使用简易计算器!"); tShow.setBounds(0, 0, 300, 20);//加法区tAdd1=new JTextField(); tAdd2=new JTextField(); tAdd3=new JTextField();label1=new JLabel("+"); label2=new JLabel("=");tAdd1.setBounds(5, 25, 80, 20); label1.setBounds(85, 25, 15, 15);tAdd2.setBounds(100,25,80,20); label2.setBounds(180,25,15,15);tAdd3.setBounds(190,25,130,20);//减法区tSub1=new JTextField(); tSub2=new JTextField(); tSub3=new JTextField();label3=new JLabel("-"); label4=new JLabel("=");tSub1.setBounds(5, 50, 80, 20); label3.setBounds(85, 50, 15, 15);tSub2.setBounds(100,50,80,20); label4.setBounds(180,50,15,15);tSub3.setBounds(190,50,130,20);//乘法区tMul1=new JTextField(); tMul2=new JTextField(); tMul3=new JTextField();label5=new JLabel("*"); label6=new JLabel("=");tMul1.setBounds(5, 75, 80, 20); label5.setBounds(85,75, 15, 15);tMul2.setBounds(100,75,80,20); label6.setBounds(180,75,15,15);tMul3.setBounds(190,75,130,20);//除法区tDiv1=new JTextField(); tDiv2=new JTextField(); tDiv3=new JTextField();label7=new JLabel("/"); label8=new JLabel("=");tDiv1.setBounds(5, 100, 80, 20); label7.setBounds(85,100, 15, 15);tDiv2.setBounds(100,100,80,20); label8.setBounds(180,100,15,15);tDiv3.setBounds(190,100,130,20);result=new JButton("开始计算");result.setBounds(10,140,100,40);exit=new JButton("退出");exit.setBounds(180,140,100,40);jp=(JPanel)this.getContentPane();jp.setLayout(null);jp.add(tShow); jp.add(tAdd1); jp.add(label1); jp.add(tAdd2); jp.add(label2); jp.add(tAdd3);jp.add(tSub1); jp.add(label3); jp.add(tSub2); jp.add(label4); jp.add(tSub3); jp.add(tMul1);jp.add(tMul2); jp.add(label5); jp.add(tMul3); jp.add(label6); jp.add(tDiv1); jp.add(label7);jp.add(tDiv2); jp.add(label8); jp.add(tDiv3); jp.add(result); jp.add(exit);//动作事件exit.addActionListener(new ActionListener(){@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stubSystem.exit(0);}});result.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){Double d = null;String a=null,b=null;a=tAdd1.getText(); b=tAdd2.getText();if(!a.isEmpty()&&!b.isEmpty()) //if(a!=null&b!=null&&a!=""&b!="")不行{d=Double.parseDouble(a)+Double.parseDouble(b);tAdd3.setText(d+""); //将d转换为字符串型// tAdd3.setText(String.valueOf(d));}a=tSub1.getText(); b=tSub2.getText();if(!a.isEmpty()&&!b.isEmpty()){d=Double.parseDouble(a)-Double.parseDouble(b);tSub3.setText(d+"");}a=tMul1.getText(); b=tMul2.getText();if(!a.isEmpty()&&!b.isEmpty()){d=Double.parseDouble(a)*Double.parseDouble(b);tMul3.setText(d+"");}a=tDiv1.getText(); b=tDiv2.getText();if(!a.isEmpty()&&!b.isEmpty()){d=Double.parseDouble(a)/Double.parseDouble(b);tDiv3.setText(String.valueOf(d));}}});}//主函数public static void main(String[] args){Calculator cal=new Calculator();cal.setVisible(true);cal.setResizable(false);cal.setSize(330,230);cal.setLocationRelativeTo(null);cal.setDefaultCloseOperation(EXIT_ON_CLOSE);}}。

eclipse实现简单计算器代码.

eclipse实现简单计算器代码.

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

计算器设计,包括数字按钮0-9,以及加减乘除法

计算器设计,包括数字按钮0-9,以及加减乘除法

使用Java Application编写满足下列要求的程序:(1)使用GridLayout布局(2)设计一个简单的计算器,包括数字按钮0-9,以及加、减、乘、除、清零,等于运算按钮和一个现实计算结果的文本区。

import java.applet.*;import java.awt.*;import java.awt.event.*;public class TestText extends Applet implements ActionListener {Label lb1,lb2;//Button btn1;Button btn2;TextField tf1;TextArea ta1;public void init(){lb1=new Label("请在文本框中输入内容!");lb2=new Label("文本区显示的内容为:");//btn1=new Button("提交");btn2=new Button("退出");tf1=new TextField(20);ta1=new TextArea();add(lb1);add(tf1);add(lb2);add(ta1);//add(btn1);add(btn2);setLayout(new FlowLayout());setSize(600,400);setVisible(true);//btn1.addActionListener(this);btn2.addActionListener(this);}public void actionPerformed(ActionEvent e){/*if(e.getSource()==btn1){ta1.setText(tf1.getText());}*/if(e.getSource()==btn2){System.exit(0);}}}(8)import java.applet.*;import java.awt.*;import java.awt.event.*;public class JiSuan extends Applet implements ActionListener{Button []buts;String names[] = {"0","1","2","3","4","5","6","7","8","9","+","-","*","/","=","置零"};TextArea text;public void init(){text = new TextArea(" ",20,2);add(text);setLayout(new GridLayout(9,4,5,5));buts = new Button[names.length];for(int i = 0;i < names.length;i++){buts[i] = new Button(names[i]);buts[i].addActionListener(this);add(buts[i]);}}static int y = 0;static float j = 0;static int z = 0;public void actionPerformed(ActionEvent e){for(int i = 0;i < 10;i++)if(e.getSource() == buts[i]){char x;x = (char)(i + '0');text.append(""+x);y = y * 10 + i;}if(e.getSource() == buts[10]) {int i = y;y = 0;j = j + i;z = 1;text.append(" + ");}if(e.getSource() == buts[11]) {int i = y;y = 0;if(j == 0)j = j + i;elsej = j - i;z = 2;text.append(" - ");}if(e.getSource() == buts[12]) {int i = y;y = 0;if(j == 0)j = j + i;elsej = j * i;z = 3;text.append(" * ");}if(e.getSource() == buts[13]) {int i = y;y = 0;if(j == 0)j = j + i;elsej = j / i;z = 4;text.append(" / ");}if(e.getSource() == buts[14]) {if(z == 1)j = j + y;else if(z == 2)j = j - y;else if(z == 3)j = j * y;elsej = j / y;text.append(" = "+j);y = 0;}if(e.getSource() == buts[15]) {text.replaceRange(" ",0,50); y = 0;j = 0;}repaint();}}。

java编写的计算器设计报告

java编写的计算器设计报告

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

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

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

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

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

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

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

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

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

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

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

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

其中后三者只对num1有效。

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

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

Java实现计算器

Java实现计算器

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

JAVA计算器源代码

JAVA计算器源代码

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

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

java实现简单的加减乘除计算器

java实现简单的加减乘除计算器

java实现简单的加减乘除计算器本⽂实例为⼤家分享了java实现加减乘除计算器的具体代码,供⼤家参考,具体内容如下代码123456 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53import java.awt.*;import java.awt.event.*;import javax.swing.*;import java.awt.FlowLayout;import javax.swing.*;@SuppressWarnings("unused")class Sumjp {JOptionPane jp = new JOptionPane();Sumjp(String str) {JOptionPane.showMessageDialog(null, str);System.exit(0);}Sumjp(String[] str){}}public class JiSuan extends JFrame implements ActionListener,ItemListener{ /****/private static final long serialVersionUID = 1L;double x1,x2,sum = 0;String f;JTextField txt = new JTextField(30);JTextField txt1 = new JTextField(5);JTextField txt2 = new JTextField(5);JTextField txt3 = new JTextField(5);JLabel lb1 = new JLabel("数据1:");JLabel lb2 = new JLabel("符号:");JLabel lb3 = new JLabel("数据2:");JButton jbtn = new JButton("确定");JiSuan(){setSize(350,150);setVisible(true);setTitle("计算器:");setDefaultCloseOperation(EXIT_ON_CLOSE);setLayout(new FlowLayout());add(lb1);add(txt1);// add(lb2);// add(txt2);JComboBox<String> jc = new JComboBox<String>();jc.addItem("加");jc.addItem("减");jc.addItem("乘");jc.addItem("除");545556575859606162636465666768697071727374757677787980818283848586878889add(jc); add(lb3);add(txt3); add(jbtn); add(txt);validate();jc.addItemListener(this);jbtn.addActionListener(this); } public void itemStateChanged(ItemEvent ie){ f = (String)ie.getItem().toString(); }public void actionPerformed(ActionEvent e){x1 = Double.parseDouble(txt1.getText());//f = txt2.getText(); x2 = Double.parseDouble(txt3.getText()); if(f.equals("加")){ sum = x1 + x2;}if(f.equals("减")){sum = x1 - x2; } if(f.equals("乘")){sum = x1*x2;}if(f.equals("")){ sum = x1/x2; }txt.setText(x1 + f + x2 + "=" + sum);new Sumjp(x1 + f + x2 + "=" + sum);}public static void main(String[] args) {// TODO ⾃动⽣成的⽅法存根new JiSuan();} }⼩编再为⼤家分享⼀段代码,感谢作者分享:利⽤java 语法做⼀个很简单的加减乘除计算器:12345678910111213/* 实现思路:1.选择所有数据从键盘输⼊2.使⽤switch 语句进⾏判断3.需要从控制台上输⼊三次 *第⼀个数字 *运算符*第⼆个数字最终在控制台上显⽰:欢迎使⽤简单计算器系统: 请输⼊第⼀个数字:10 请输⼊运算符:+1415161718192021222324252627282930313233343536373839404142434445464748495051525354请输⼊第⼆个数字:20运算结果:10+20=30s.nextInt(); */public class Calculator {public static void main(String[] args){java.util.Scanner s = new java.util.Scanner(System.in); System.out.println("欢迎使⽤简单计算器");System.out.print("请输⼊第⼀个数字:"); int num1 = s.nextInt();System.out.print("请输⼊运算符:"); String operator = s.next(); System.out.print("请输⼊第⼆个数字:"); int num2 = s.nextInt();int result = 0;switch (operator){case "+":result = num1 + num2;break;case "-":result = num1 - num2; break; case "*": result = num1 * num2; break;case "/":result = num1 * num2;break;case "%": result = num1 % num2; } System.out.println(num1+operator+num2+"="+result); }}以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。

java简易计算器完整代码

java简易计算器完整代码

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

(完整word版)java设计的房贷计算器

(完整word版)java设计的房贷计算器
yuehuankuan = zonge1 / nian / 12 ;
for(int i=1;i <= nian*12;i++){
yuehuanbenjin =benjin / nian /12;
yuehuankuan = (int) (yuehuanbenjin + lilv / nian / 12 *(nian * 12 - i)*yuehuanbenjin*0.01);
System.out.println("3。退出-> C *");
System.out.println("************************************************"); //菜单提示
double lilv;
double benjin;
int nian;
int yuehuankuan;
Scanner reader1=new Scanner(System.in);
System.out.print("请输入年利率:");
lilv= reader1.nextInt();
System.out.print("请输入贷款总额:");
benjin= reader1.nextDouble();
System.out.print("请输入还款年限:");
//java编写的房贷计算器ห้องสมุดไป่ตู้
//@王强出品
import java.util.*;
public class fangdai {
public static void main(String args[]) throws InterruptedException

简单计算器程序设计

简单计算器程序设计

《网络编程技术》结课论文2012 — 2013学年第二学期题目:简单计算器程序专业班级:网信10-2学号:************姓名:-----------指导老师:---------日期:2013-06-25目录1引言 (3)2基础理论 (3)2.1 AWT 组件 (3)2.2 Swing 组件 (3)2.3 java事件处理机制 (4)3 功能设计 (5)3.1计算器系统概述 (5)3.2功能模块设计 (6)3.3详细设计 (6)4 系统实现 (7)4.1需求分析 (7)4.2设计思路 (8)4.3主要代码展示及说明 (8)4.4调试与分析 (12)5 总结 (12)参考文献 (13)1引言近年来随着计算机和网络在社会领域的发展,java的应用正在不断地走向深入, Java语言的优良特性使得Java应用具有无比的健壮性和可靠性,这也减少了应用系统的维护费用。

Java对对象技术的全面支持和Java平台内嵌的API能缩短应用系统的开发时间并降低成本。

Java的编译一次,到处可运行的特性使得它能够提供一个随处可用的开放结构和在多平台之间传递信息的低成本方式。

特别是Java企业应用编程接口为企业计算及电子商务应用系统提供了有关技术和丰富的类库。

本次设计是通过java编程技术来设计一个图形界面(GUI)的计算器应用程序,完成简单的算术运算,该计算器可以实现加法、减法、乘法、除法的简单运算,也可以实现一些简单的扩展运算,这次课程设计的主要目的在于检测对java 应用的熟练程度,发现问题并及时改正和提高,同时扩展对java知识的进一步了解和认识,强化自己的编程能力,为将来在新的旅途中能更好的发挥自身的才能!2基础理论2.1 AWT 组件布局管理器管理组件如何放置在容器中,AWT 中最常用的四种布局类:FlowLayout、BorderLayout、GridLayout、CardLayout。

本项目主要采用了GridLayout 布局。

java编写一个贷款计算器

java编写一个贷款计算器

java编写⼀个贷款计算器https:///flueky/article/details/77099454 房贷有两种贷款⽅式:1是等额本息还款;2是等额本⾦还款。

简单的说就是等额本息就是每⽉还款额相等,⽐如⼀个⽉固定还款3000元,每⽉不变,就是这种等额本息还款的⽅式。

另外⼀种就是每⽉还款额不等,⼀个⽉⽐⼀个⽉少点。

但是还款初期还款额⽐较⼤,越往后还款越少。

具体哪种适合⾃⼰要结合⾃⾝的情况。

如果看利息的话第⼆种还款总利息要少于第⼀种。

好了我们现在再说⼀下两者还款的计算⽅式: (⼀)等额本息还款: 每⽉还本付息=【贷款本⾦x⽉利率x(1+⽉利率)^还款⽉数】/【(1+⽉利率)^还款⽉数-1】 每⽉还利息=剩余本⾦x贷款⽉利率(第⼀个⽉的本⾦就是贷款额,逐⽉递减) 每⽉还款本⾦=每⽉还款⾦额-每⽉还利息 剩余本⾦=上⽉剩余本⾦-本⽉偿还本⾦ 还款总利息=贷款额X贷款⽉数x⽉利率x(1+⽉利率)^还款⽉数/【(1+还款⽉数)^还款⽉数-1】-贷款总额 注:^这个符号是次⽅的意思 主要计算公式就是这样,等额本息公式详细推导过程并不是很难,应⽤⾼中阶段的数学知识就可以完全理解清楚。

(⼆)等额本⾦还款 每⽉还本付息=(本⾦/还款⽉数)+(本⾦-累计已还本⾦)x⽉利率 每⽉本⾦=总本⾦/还款⽉数 每⽉利息=(本⾦-累计已还本⾦)x⽉利率 还款总利息=(还款⽉数+1)x贷款额x⽉利率/2java编写⼀个简易版贷款计算器1 import javax.swing.*;2 import java.awt.*;3 import java.awt.event.*;4 import javax.swing.border.*;56 public class LoanCalculator extends JFrame {7 private class ButtonListener implements ActionListener {8 @Override9 public void actionPerformed(ActionEvent e) {10 // TODO Auto-generated method stub11 double interest=12 Double.parseDouble(jtfAnnualInterestRate.getText());13 int year=14 Integer.parseInt(jtfNumberOfYears.getText());15 double loanAmount=16 Double.parseDouble(jtfLoanAmount.getText());1718 double monthlyInterest=interest/1200;19 double monthlyPayment= loanAmount*monthlyInterest/(1-1/Math.pow(1+monthlyInterest,20 year*12));21 double totalPayment=monthlyPayment*year*12;2223 jtfMonthlyPayment.setText(String.format("%.2f", monthlyPayment));24 jtfTotalPayment.setText(String.format("%.2f", totalPayment));25 }26 }2728 private JTextField jtfAnnualInterestRate=new JTextField();29 private JTextField jtfNumberOfYears=new JTextField();30 private JTextField jtfLoanAmount=new JTextField();31 private JTextField jtfMonthlyPayment=new JTextField();32 private JTextField jtfTotalPayment=new JTextField();3334 private JButton jbtComputeLoan=new JButton("Compute Payment");3536 public LoanCalculator(){37 JPanel p1=new JPanel(new GridLayout(5,2));38 p1.add(new JLabel("Annual Interest Rate"));39 p1.add(jtfAnnualInterestRate);40 p1.add(new JLabel("Number of Years"));41 p1.add(jtfNumberOfYears);42 p1.add(new JLabel("Loan Amount"));43 p1.add(jtfLoanAmount);44 p1.add(new JLabel("Monthly Payment"));45 p1.add(jtfMonthlyPayment);46 p1.add(new JLabel("Total Payment"));47 p1.add(jtfTotalPayment);48 p1.setBorder(new TitledBorder("Enter loan amount, interest rate,"49 + " and year"));5051 JPanel p2=new JPanel(new FlowLayout(FlowLayout.RIGHT));52 p2.add(jbtComputeLoan);53 add(p1,BorderLayout.CENTER);54 add(p2,BorderLayout.SOUTH);55 jbtComputeLoan.addActionListener(new ButtonListener());5657 }5859 public static void main(String[] args) {60 // TODO Auto-generated method stub61 LoanCalculator frame=new LoanCalculator();62 frame.setTitle("LoanCalculator");63 frame.pack();64 frame.setLocationRelativeTo(null);65 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);66 frame.setVisible(true);67 }6869 }另⼀种编写⽅式:https:///flueky/article/details/77099454注:利率⼀律按照4.9计算。

java简易计算机代码

java简易计算机代码

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

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

我们需要定义一个Calculator类,代码如下:```javapublic class Calculator {// 定义两个整型变量,用于存储输入的数字private int num1;private int num2;// 构造方法,用于初始化Calculator对象public Calculator(int num1, int num2) {this.num1 = num1;this.num2 = num2;}// 加法运算方法public int add() {return num1 + num2;}// 减法运算方法public int subtract() {return num1 - num2;}// 乘法运算方法public int multiply() {return num1 * num2;}// 除法运算方法public double divide() {// 判断除数是否为0,避免除以0的错误if (num2 != 0) {return (double)num1 / num2;} else {System.out.println("除数不能为0!");return 0;}}// 主方法,程序入口public static void main(String[] args) {// 创建一个Calculator对象,传入两个待计算的数值Calculator calculator = new Calculator(10, 5);// 调用加法运算方法,并输出结果int sum = calculator.add();System.out.println("两数之和:" + sum);// 调用减法运算方法,并输出结果int difference = calculator.subtract();System.out.println("两数之差:" + difference);// 调用乘法运算方法,并输出结果int product = calculator.multiply();System.out.println("两数之积:" + product);// 调用除法运算方法,并输出结果double quotient = calculator.divide();if (quotient != 0) {System.out.println("两数之商:" + quotient);}}}```在上面的代码中,我们首先定义了一个Calculator类,包含了两个私有的整型变量num1和num2,用于存储输入的数字。

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

用java写了一个简单计算器,能实现简单的数据计算。

一、先写界面代码:在UI包里面新建一个Class文件,取名自己想,这里我写的是CalculatorFrame package ui;import java.awt.Color;import java.awt.Font;import java.awt.GridLayout;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JOptionPane;import javax.swing.JPanel;import javax.swing.JScrollPane;import javax.swing.JTextArea;import javax.swing.border.TitledBorder;public class CalculatorFrame extends JFrame {private static final long serialVersionUID = 1L;public String opt;public String str;private JTextArea show;private ClientContext clientContext;//引用控制器对象/*因为调用了控制器里面的方法,所以要对控制器的对象进行赋值,否则运行会出现空指针异常*/public void setClientContext(ClientContext clientContext) {this.clientContext = clientContext;}public CalculatorFrame() {init();}private void init() {setTitle(" Simple Calculator");setBounds(533, 184, 300, 400);setContentPane(creatContentPane());}private JPanel creatContentPane() {JPanel p = new JPanel(new GridLayout(4, 1)); /* 在面板里面添加4个面板*/p.add(showPane());//显示屏p.add(btnPane1());//下面三个都是按钮p.add(btnPane2());p.add(btnPane3());return p;}/*实现各个面板*/private JScrollPane showPane() {JScrollPane p = new JScrollPane();p.setBorder(new TitledBorder("Display:"));show = new JTextArea();show.setFont(new Font("",Font.PLAIN,25));show.setForeground(Color.RED);show.setLineWrap(true);show.setEditable(false);p.getViewport().add(show);return p;}private JPanel btnPane1() {JPanel p = new JPanel(new GridLayout(2, 4));JButton add = new JButton("+");JButton jian = new JButton("-");JButton cheng = new JButton("*");JButton chu = new JButton("/");JButton one = new JButton("1");JButton two = new JButton("2");JButton three = new JButton("3");JButton anser = new JButton("=");p.add(add);p.add(jian);p.add(cheng);p.add(chu);p.add(one);p.add(two);p.add(three);p.add(anser);/*用内部类实现按钮监视器,后面的都是这样*/ one.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent arg0) {String number = show.getText() + String.valueOf(1);//按了数字“1”按//钮后,操作显示屏,既更新一下显示屏clientContext.setNumber(number);//调用控制器里面的方法}});two.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent arg0) {String number = show.getText() + String.valueOf(2);;clientContext.setNumber(number);}});three.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stubString number = show.getText() + String.valueOf(3);clientContext.setNumber(number);}});add.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent arg0) {opt = "+";clientContext.setOpt(opt);}});jian.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stubopt = "-";clientContext.setOpt(opt);}});cheng.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stubopt = "*";clientContext.setOpt(opt);}});chu.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stubopt = "/";clientContext.setOpt(opt);}});anser.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent arg0) { str = "=";clientContext.setAnswer(str);}});return p;}private JPanel btnPane2() {JPanel p = new JPanel(new GridLayout(2, 4));JButton four = new JButton("4");JButton five = new JButton("5");JButton six = new JButton("6");JButton pi = new JButton("PI");JButton seven = new JButton("7");JButton eight = new JButton("8");JButton nine = new JButton("9");JButton com = new JButton(".");p.add(four);p.add(five);p.add(six);p.add(pi);p.add(seven);p.add(eight);p.add(nine);p.add(com);four.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stubString number = show.getText() + String.valueOf(4);clientContext.setNumber(number);}});five.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stubString number = show.getText() + String.valueOf(5);clientContext.setNumber(number);}});six.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stubString number = show.getText() + String.valueOf(6);clientContext.setNumber(number);}});seven.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stubString number = show.getText() + String.valueOf(7);clientContext.setNumber(number);}});eight.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stubString number = show.getText() + String.valueOf(8);clientContext.setNumber(number);}});nine.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stubString number = show.getText() + String.valueOf(9);clientContext.setNumber(number);}});com.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stubsetShow(show.getText() + ".");}});pi.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stubsetShow(String.valueOf(Math.PI));}});return p;}private JPanel btnPane3() {JPanel p = new JPanel(new GridLayout(2, 4));JButton zero = new JButton("0");JButton sqrt = new JButton("√");JButton guiling = new JButton("C");final JButton help = new JButton("Help");p.add(zero);p.add(sqrt);p.add(guiling);p.add(help);help.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stubJOptionPane.showMessageDialog(help, "注意:假如第二运算数为空的话,这里将默认为0.0!");}});guiling.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stubclientContext.setMc();}});zero.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stubString number = show.getText() + String.valueOf(0);clientContext.setNumber(number);}});sqrt.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stubsetShow("" + Math.sqrt(getShow()));}});return p;}/*更新计算器的显示屏*/public void setShow(String str) {show.setText(str);}/*获取当前显示屏里面的数据*/public Double getShow() {String str = show.getText();if (str.equals("")) {str = "0.0";}return Double.valueOf(str);}/*获取当前选择的运算符:比如加或减或乘或除*/public String getOpt() {return this.opt;}}二、写控制器代码在UI包建立一个Class,我取名ClientContextpackage ui;import java.util.ArrayList;import java.util.List;import javax.swing.JOptionPane;public class ClientContext {private CalculatorFrame calculatorFrame;private Double first = 0.0;private Double next = 0.0;public void setCalculatorFrame(CalculatorFrame calculatorFrame) { this.calculatorFrame = calculatorFrame;}double sum = 0;public void setNumber(String str) {calculatorFrame.setShow(str);}public void setOpt(String opt) {first = calculatorFrame.getShow();calculatorFrame.setShow("");}public void setAnswer(String str) {//按了“=”后,对数据按运算符进行计算next = calculatorFrame.getShow();// calculatorFrame.setShow(str);// switch(str){//// }if (calculatorFrame.getOpt() == "+") {double answer = first + next;calculatorFrame.setShow(String.valueOf(answer));} else if (calculatorFrame.getOpt() == "-") {double answer = first - next;calculatorFrame.setShow(String.valueOf(answer));} else if (calculatorFrame.getOpt() == "*") {double answer = first * next;calculatorFrame.setShow(String.valueOf(answer));} else if (calculatorFrame.getOpt() == "/") {if (next == 0) {calculatorFrame.setShow("对不起,除数不能为0");} else {double answer = first / next;calculatorFrame.setShow(String.valueOf(answer));}} else {calculatorFrame.setShow(String.valueOf(calculatorFrame.getShow()));}}public void setMc() {// TODO Auto-generated method stubcalculatorFrame.setShow("");first = 0.0;next = 0.0;calculatorFrame.opt=null;}}三、写主方法在Client包里面新建Class,我取名Mainpackage client;import javax.swing.JOptionPane;import ui.CalculatorFrame;import ui.ClientContext;public class Main {/*** @param args*/public static void main(String[] args) {// TODO Auto-generated method stubCalculatorFrame c = new CalculatorFrame();c.setVisible(true);ClientContext clientContext = new ClientContext();c.setClientContext(clientContext);clientContext.setCalculatorFrame(c);}}最后运行后如下:。

相关文档
最新文档