用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 简单实用计算器代码

//JSQ.javaimport java.awt.*;import java.awt.event.*;import javax.swing.*;public class JSQ{public static void main(String args[]){new MyJSQ("My计算器");}}class MyJSQ extends Frame implements ActionListener{JButton bOption,bNumber;TextField Tresult;int flag=0,perflag;//perflag表示单击了那一个运算符,1表示"+",2表示"-",3表示"*",4表示"/"double op1=0.0,op2=0.0;//操作数StringBuffer str=new StringBuffer();//显示屏所显示的字符串MyJSQ(String s){setTitle(s);Panel conPanel=new Panel();conPanel.setLayout(new BorderLayout());//设置显示屏Panel ptop=new Panel();Tresult=new TextField("0",20);Tresult.setEditable(false);//不可编辑性ptop.add(Tresult);conPanel.add(ptop,BorderLayout.NORTH);//总按键面板Panel pButton=new Panel();Cursor cs=Cursor.getPredefinedCursor(Cursor.HAND_CURSOR);setCursor(cs);pButton.setLayout(new BorderLayout());//操作面板1Panel pUp=new Panel();pUp.setLayout(new GridLayout(2,5,1,1));//(行数,列数,水平间距,垂直间距)bOption=new JButton("x^3");bOption.setForeground(Color.gray);bOption.setMargin(new Insets(3,1,3,5));//setMargin()设置按钮边框和标签之间的空白。

JAVA简易计算器程序源代码

JAVA简易计算器程序源代码

JAVA简易计算器程序源代码package myText;import java.awt.*;import javax.swing.*;import java.awt.event.*;import javax.swing.border.*;public class Calculator extends JFrame implements ActionListener{ private JPanel Panel1=new JPanel();private JPanel Panel2=new JPanel();private JTextField tfResult=new JTextField(25);private JLabel label=new JLabel("计算结果:");private String recentOperation=null;private String recentNum=null;private boolean isNew=true;public void addButton(Container c,String s){JButton b=new JButton(s);b.setFont(new java.awt.Font("SansSerif",0,12));b.setForeground(Color.red);b.setBorder(BorderFactory.createRaisedBevelBorder());c.add(b);b.addActionListener(this);}//end public void addButton(Container c,String s)public void actionPerformed(ActionEvent e){String s=e.getActionCommand();if(s.charAt(0)>='0'&&s.charAt(0)<='9'){if(!isNew){tfResult.setText(tfResult.getText()+s);}//end if(!isNew)else{tfResult.setText(s);}//end elseisNew=false;}//end if(s.charAt(0)>='0'&&s.charAt(0)<='9') else if(s.equals(".")){if(tfResult.getText().indexOf(".")!=-1)return;if(!isNew&&tfResult.getText()!=""){tfResult.setText(tfResult.getText()+".");}//end ifelse{tfResult.setText("0.");}//end elseisNew=false;}//end if(s.equals("."))else if(s.equals("=")){equalaction(e);}//end if(s.equals("="))else{if((tfResult.getText()).equals("")){return;}//endif((tfResult.getText()).equals(""))if(recentOperation!=null){equalaction(e);}//end if(recentOperation!=null) recentOperation=s;recentNum=tfResult.getText();isNew=true;}//end else}//end public void actionPerformed(ActionEvent e) void equalaction(ActionEvent e){if(recentOperation==null||recentNum==null||tfResult.getTex t().equals("")){ return;}//end if()double last=0,now=0;try{last=Double.parseDouble(recentNum);now=Double.parseDouble(tfResult.getText());}//end trycatch(NumberFormatException ne){recentOperation=null;recentNum=null;tfResult.setText("数据输入不合法");System.out.println("数据输入不合法");isNew=true;return;}//end catch(NumberFormatException ne)if(recentOperation.equals("+")){last+=now;}//end if(recentOperation.equals("+"))if(recentOperation.equals("-")){last-=now;}//endif(recentOperation.equals("-"))if(recentOperation.equals("*")){last*=now;}//endif(recentOperation.equals("*"))if(recentOperation.equals("/")){last/=now;}//endif(recentOperation.equals("/"))tfResult.setText(""+last);recentNum=tfResult.getText();recentOperation=null;isNew=true;}//end void equalaction(ActionEvent e)public Calculator(){tfResult.setBorder(BorderFactory.createLoweredBevelBorder ());tfResult.setEditable(false);tfResult.setText("0");tfResult.setHorizontalAlignment(SwingConstants.RIGHT);////本java源代码由839682048整理修改//////Panel1.add(label,FlowLayout.LEFT);Panel1.add(tfResult);////本java源代码由839682048整理修改///Panel2.setLayout(new GridLayout(4,4,2,2));String buttons="789/456*123-0.=+";for(int i=0;i<buttons.length();i++){< p="">addButton(Panel2,buttons.substring(i,i+1));}//end for()//本java源代码由839682048整理修改///this.getContentPane().add(Panel1,"North");this.getContentPane().add(Panel2,"Center");this.setResizable(false);this.setTitle("计算器");this.addWindowListener(newjava.awt.event.WindowAdapter(){public void windowClosing(WindowEvent e){System.exit(0);}});}//end public Calculator1()public static void main(String[]args){Calculator mf=new Calculator();mf.setBounds(200,200,400,400);mf.show();}//end main()}//end public class Calculator1extends JFrame implements ActionListener</buttons.length();i++){<>。

用java编写简单计算器

用java编写简单计算器

用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);JclientContext.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 stub opt = "-";clientContext.setOpt(opt);}});cheng.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub opt = "*"; clientContext.setOpt(opt);}});chu.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub opt = "/";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-generatedmethod 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 stub setShow(show.getText() + ".");}});pi.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub setShow(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 JButto n(”V");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 stub JOptionPane.showMessageDialog(help, " 注意:假如第二运算数为空的话,这里将默认为0.0 !");}});guiling.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stub clientContext.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 stub calculatorFrame.setShow("");first = 0.0;next = 0.0;calculatorFrame.opt=null;}}三、写主方法在Client 包里面新建Class ,我取名Main package 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);}最后运行后如下:。

java简单计算器源代码

java简单计算器源代码

简单计算器代码package calcultorthree;import java.awt.BorderLayout;//导入边界布局管理器类import java.awt.GridLayout;//导入网格布局管理器类import java.awt.T extField;//导入文本区域类import java.awt.event.ActionEvent;//导入事件类import java.awt.event.ActionListener;//导入事件监听者类import javax.swing.JButton;//导入按钮类import javax.swing.JFrame;//导入窗体import javax.swing.JPanel;//导入面板/***本例实现了简单计算器代码,具备加减乘除和正弦功能,旨在抱砖引玉。

熟悉java的同学,可以在此基础上实现更复杂的功能。

* author Fjsh*/public class CalcultorThree {//新建对象,在构造函数中进行初始化JFrame frame;//新建窗体对象JButton buttonzero,buttondot,buttonequal;//新建按钮“0”“.”“=”JButton buttonplus,buttonminus,buttonmultiple,buttondevision,buttonsin,buttontozero;//新建按钮“+”“-”“*”“/”“sin”和归零按钮JButton buttonone,buttontwo,buttonthree,buttonfour,buttonfive,buttonsix, buttonseven,buttoneight,buttonnine;//新建数字按钮“0”“1”“2”“3”“4”“5”“6”“7”“8”“9”JPanel panelwest,panelcenter,paneleast;//新建三个面板T extField tf;//新建文本区域对象public CalcultorThree(){//初始化对象tf=new T extField(30);//构造空文本字段,字符宽度为30frame =new JFrame("CalculatorThree");//构造窗体对象,名称为“CalculatorThree”panelcenter=new JPanel();//构造面板,放到窗体中央panelwest=new JPanel();//构造面板,放到窗体西边paneleast=new JPanel();//构造面板,放到窗体东边Handle h=new Handle();//新建Handle类对象,Handle类为事件监听类//创建数字按钮对象,1、2、3、4、5、6、7、8、9buttonone=new JButton("1");buttontwo=new JButton("2");buttonthree=new JButton("3");buttonfour=new JButton("4");buttonfive=new JButton("5");buttonsix=new JButton("6");buttonseven=new JButton("7");buttoneight=new JButton("8");buttonnine=new JButton("9");panelcenter.setLayout(new GridLayout(3,3));//设置面板布局为网格布局,3行3列//将数字按钮添加到中间面板panelcenter.add(buttonone);panelcenter.add(buttontwo);panelcenter.add(buttonthree);panelcenter.add(buttonfour);panelcenter.add(buttonfive);panelcenter.add(buttonsix);panelcenter.add(buttonseven);panelcenter.add(buttoneight);panelcenter.add(buttonnine);//为10个按钮注册事件监听器buttonone.addActionListener(h);buttontwo.addActionListener(h);buttonthree.addActionListener(h);buttonfour.addActionListener(h);buttonfive.addActionListener(h);buttonsix.addActionListener(h);buttonseven.addActionListener(h);buttoneight.addActionListener(h);buttonnine.addActionListener(h);//构造按钮“0”“.”“=”,注册事件监听器,设置1行3列的布局,添加到到西边的面板buttonzero=new JButton("0");buttondot=new JButton(".");buttonequal=new JButton("=");buttonzero.addActionListener(h);buttondot.addActionListener(h);buttonequal.addActionListener(h);panelwest.setLayout(new GridLayout(3,1));panelwest.add(buttonzero);panelwest.add(buttondot);panelwest.add(buttonequal);//构造操作按钮“+”“-”“*”“/”“sin”“>0”,其中“>0”为归零按钮buttonplus=new JButton("+");buttonminus=new JButton("-");buttonmultiple=new JButton("*");buttondevision=new JButton("/");buttonsin=new JButton("sin");buttontozero=new JButton(">0");paneleast.setLayout(new GridLayout(3,1));//设置西边的布局为3行1列//将操作按钮“+”“-”“*”“/”“sin”“>0”添加到西边的面板中paneleast.add(buttonplus);paneleast.add(buttonminus);paneleast.add(buttonmultiple);paneleast.add(buttondevision);paneleast.add(buttonsin);paneleast.add(buttontozero);//为操作按钮“+”“-”“*”“/”“sin”“>0”注册监听器buttonplus.addActionListener(h);buttonminus.addActionListener(h);buttonmultiple.addActionListener(h);buttondevision.addActionListener(h);buttonsin.addActionListener(h);buttontozero.addActionListener(h);frame.setLayout(new BorderLayout());//设置窗体为边界布局frame.add(paneleast,"East");//将东边面板paneleast添加到窗体的东边frame.add(tf,BorderLayout.NORTH); //将tf文本区域添加到窗体的北边,即顶部frame.add(panelwest,BorderLayout.WEST);//将panelwest面板添加到窗体西边frame.add(panelcenter,BorderLayout.CENTER);//将panelcenter面板添加到窗体中间frame.pack();//设置窗体大小,适合其子组件的首选大小和布局frame.setLocation(500,500);//设置窗体显示位置为(500,500)frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//设置布局窗体默认关闭方式frame.setVisible(true);//设置窗体可见}public static void main(String[] args) {new CalcultorThree();//主方法中新建对象}class Handle implements ActionListener{//实现动作监听器类int biaozhi=0;//此标志标志加减乘除操作double flag1=0,flag2=0,flag3=0;//flag1、flag2为两个操作数,flag3为结果Overridepublic void actionPerformed(ActionEvent e) { //方法重写try{//此处可能会产生异常,用try、catch捕捉异常,不用处理if(e.getSource()==buttondot){//小数点tf.setT ext("0.");}if(e.getSource()==buttontozero){//归零操作tf.setT ext("");}if(e.getSource()==buttonzero){//按键0操作tf.setT ext(tf.getT ext()+"0");flag1=Double.parseDouble(tf.getT ext());//将文本区域转换成Double类型,赋给flag1}if(e.getSource()==buttonone){//按键1操作tf.setT ext(tf.getT ext()+"1");flag1=Double.parseDouble(tf.getT ext());}else if(e.getSource()==buttontwo){//按键2操作tf.setT ext(tf.getT ext()+"2");flag1=Double.parseDouble(tf.getT ext());}else if(e.getSource()==buttonthree){//按键3操作tf.setT ext(tf.getT ext()+"3");flag1=Double.parseDouble(tf.getT ext());}else if(e.getSource()==buttonfour){//按键4操作tf.setT ext(tf.getT ext()+"4");flag1=Double.parseDouble(tf.getT ext());}else if(e.getSource()==buttonfive){//按键5操作tf.setT ext(tf.getT ext()+"5");flag1=Double.parseDouble(tf.getT ext());}else if(e.getSource()==buttonsix){//按键6操作tf.setT ext(tf.getT ext()+"6");flag1=Double.parseDouble(tf.getT ext());}else if(e.getSource()==buttonseven){//按键7操作tf.setT ext(tf.getT ext()+"7");flag1=Double.parseDouble(tf.getT ext());}else if(e.getSource()==buttoneight){//按键8操作tf.setT ext(tf.getT ext()+"8");flag1=Double.parseDouble(tf.getT ext());}else if(e.getSource()==buttonnine){//按键9操作tf.setT ext(tf.getT ext()+"9");flag1=Double.parseDouble(tf.getT ext());}if(e.getSource()==buttonplus){//加法操作tf.setT ext("");flag2=flag1;biaozhi=0;}if(e.getSource()==buttonminus){//减法操作tf.setT ext("");flag2=flag1;biaozhi=1;}if(e.getSource()==buttonmultiple){//乘法操作tf.setT ext("");flag2=flag1;biaozhi=2;}if(e.getSource()==buttondevision){//除法操作tf.setT ext("");flag2=flag1;biaozhi=3;}if(e.getSource()==buttonsin){//正弦操作flag3=Math.sin(flag1);tf.setT ext(flag3+"");}if(e.getSource()==buttonequal){//等号操作,利用biaozhi判断进行相应加减乘除操作if(biaozhi==0){flag3=flag1+flag2;}if(biaozhi==1){flag3=flag1-flag2;}if(biaozhi==2){flag3=flag1*flag2;}if(biaozhi==3){flag3=flag1/flag2;}tf.setT ext(flag3+""); }}catch(Exception ex){}}}}。

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简单计算器--代码
JOptionPane.ERROR_MESSAGE);return;}
}
}
if(act.equals("sqrt")){try{float num=(float)Math.sqrt(Float.parseFloat(t.getText()));
t.setText(String.valueOf(num));can=true;return;
JOptionPane.ERROR_MESSAGE);return;}
}
}
public float cacu(float a,char c,float b){
float sum;
switch(c){
case '+':sum=a+b;break;
case '-':sum=a-b;break;
t.setText(String.valueOf(num));can=true;return;
}catch(NumberFormatException e1){JOptionPane.showMessageDialog(null, "输入格式错误!", "警告!",
JOptionPane.ERROR_MESSAGE);return;}
p1.add(backButton);
p1.add(clearButton);
backButton.addActionListener(this);
clearButton.addActionListener(this);
p2.add(t);
p2.add(p1);
p2.setBackground(Color.black);

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

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

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

java-Swing计算器代码

java-Swing计算器代码
import;
import;
import;
import;
/**
*计算器
*@authorliandyao
*
*/
publicclassCalcFrameTestextendsJFrame{
/**
*计算器窗体的宽度
*/
publicfinalstaticintJF_WIDTH= 300 ;
/**
*计算器窗体的高度
this.setLocationRelativeTo(null) ;//设置在屏幕的中心
this.setResizable(false) ;
c=this.getContentPane() ;
c.setLayout(null) ;
init();//初始化界面
this.setVisible(true) ;
*/
/**
*第3行排列
*/
JButtonjb1 =newJButton("1") ;
jb1.setBounds(30, 150,BT_WIDTH,BT_HEIGHT) ;
//加入数字按钮事件
jb1.addActionListener(numberListenere) ;
c.add(jb1) ;
JButtonjb2 =newJButton("2") ;
*
*/
classOpertorActionListenerimplementsActionListener{
@Override
publicvoidactionPerformed(ActionEvente) {
JButtonj = (JButton)e.getSource() ;//事件的源

用java编写一个简易的计算器代码复习课程

用java编写一个简易的计算器代码复习课程

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

Java实现计算器

Java实现计算器

Java实现简易计算器,可以计算算术表达式: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代码写的简易计算器(可以实现基本的加减乘除功能)

java代码写的简易计算器(可以实现基本的加减乘除功能)计算器java写⼀个计算器,要求实现加减乘除功能,并且能够循环接收新的数据,通过⽤户交互实现。

import java.util.Scanner;/*** 计算器* 写4个⽅法:加减乘除* 利⽤循环加switch进⾏⽤户交互* 传递需要操作的两个数* 输出结果*/public class Demo04 {public static double a;public static double b;//运算符public static String operator;//=符public static String equal;//结果public static double sum=0;public static void main(String[] args) {Scanner scanner = new Scanner(System.in);System.out.println("输⼊数字:");a = scanner.nextDouble();System.out.println("输⼊运算符:");operator = scanner.next();System.out.println("输⼊数字:");b = scanner.nextDouble();do {switch (operator){case "+":sum= add(a, b);System.out.println("输⼊=获取结果:");equal = scanner.next();coninue();break;case "-":sum=subtract(a,b);System.out.println("输⼊=获取结果:");equal = scanner.next();coninue();break;case "*":sum=multiply(a,b);System.out.println("输⼊=获取结果:");equal = scanner.next();coninue();break;case "/":if (b==0){System.out.println("被除数不能为0");operator = "q";break;}else {sum=divide(a,b);System.out.println("输⼊=获取结果:");equal = scanner.next();coninue();break;}default:System.out.println("运算符输⼊错误!");}}while (operator.equals("+")||operator.equals("-")||operator.equals("*")||operator.equals("/"));scanner.close();}//加public static double add(double a,double b){return a+b;}//减public static double subtract(double a,double b){return a-b;}//乘public static double multiply(double a,double b){return a*b;}//除public static double divide(double a,double b){return a/b;}//获得结果或再次输⼊public static void coninue(){Scanner scanner = new Scanner(System.in);if (equal.equals("=")){System.out.println(a+operator+b+"="+sum);System.out.println("输⼊运算符+,-,*,/继续或输⼊其他字符结束");operator=scanner.next();if (operator.equals("+")||operator.equals("-")||operator.equals("*")||operator.equals("/")){ System.out.println("输⼊数字:");b = scanner.nextDouble();a=sum;}else {System.out.println("输⼊错误!");}}else {System.out.println("输⼊错误!");}}}。

Java制作简易计算器

Java制作简易计算器

Java制作简易计算器(代码)import java.awt.*;import javax.swing.*;import java.awt.event.*;import javax.swing.*;//GUi之前要吧这两个都引进来public class Computer extends JFrame implements ActionListener{//定义组件JButton a1,a2,a3,a4,a5,a6,a7,a8,a9,a0;JButton b1,b2,b3,b4;JButton c1,c2,c3,c4;JTextField t1,t2;JPanel p1,p2;JLabel bq1,bq2;String fuhao;Double count,count2;boolean chose=false,cliks;public static void main(String[] args){Computer l = new Computer();}public Computer(){Font font = new Font("宋体", Font.BOLD, 36);Font font2 = new Font("宋体", Font.BOLD, 20);//实例化组件a1 = new JButton("1");a1.setFont(font);a1.addActionListener(this);a2 = new JButton("2");a2.setFont(font);a2.addActionListener(this);a3 = new JButton("3");a3.setFont(font);a3.addActionListener(this);a4 = new JButton("4");a4.setFont(font);a4.addActionListener(this);a5 = new JButton("5");a5.setFont(font);a5.addActionListener(this); a6 = new JButton("6");a6.setFont(font);a6.addActionListener(this); a7 = new JButton("7");a7.setFont(font);a7.addActionListener(this); a8 = new JButton("8");a8.setFont(font);a8.addActionListener(this); a9 = new JButton("9");a9.setFont(font);a9.addActionListener(this); a0 = new JButton("0");a0.setFont(font);a0.addActionListener(this);b1 = new JButton("清空");b1.addActionListener(this); b2 = new JButton("返回");b2.addActionListener(this); b3 = new JButton(".");b3.addActionListener(this);b4 = new JButton("=");b4.addActionListener(this);c1 = new JButton("+");c1.addActionListener(this);c2 = new JButton("-");c2.addActionListener(this); c3 = new JButton("x");c3.addActionListener(this); c4 = new JButton("÷");c4.addActionListener(this);t1 = new JTextField(25);t2 = new JTextField(35);t1.setFont(font2);t2.setFont(font2);p1 = new JPanel();p2 = new JPanel();bq1 = new JLabel("结");bq2 = new JLabel("果");p1.setLayout(new GridLayout(2,3));p2.setLayout(new GridLayout(4,4));//添加组件p1.add(t1);p1.add(b1);p1.add(b2);p1.add(t2);p1.add(bq1);p1.add(bq2 );p2.add(a1);p2.add(a2);p2.add(a3);p2.add(c1);p2.add(a4);p2.add(a5);p2.add(a6);p2.add(c2);p2.add(a7);p2.add(a8);p2.add(a9);p2.add(c3);p2.add(b3);p2.add(a0);p2.add(b4);p2.add(c4);this.add(p1,BorderLayout.NORTH);this.add(p2,BorderLayout.CENTER);//设置窗口属性this.setSize(460,380);this.setTitle("简易计算器");this.setLocation(200,200);this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);this.setVisible(true);}//事件响应public void actionPerformed(ActionEvent e){Object temp = e.getSource();if(temp == a1){if(chose==true){t1.setText("");t2.setText("");}t1.setText(t1.getText()+""+"1");chose=false;}if(temp == a2){if(chose==true){t1.setText("");t2.setText("");}t1.setText(t1.getText()+""+"2");chose=false;}if(temp == a3){if(chose==true){t1.setText("");t2.setText("");} t1.setText(t1.getText()+""+"3");chose=false;}if(temp == a4){if(chose==true){t1.setText("");t2.setText("");} t1.setText(t1.getText()+""+"4");chose=false;}if(temp == a5){if(chose==true){t1.setText("");t2.setText("");} t1.setText(t1.getText()+""+"5");chose=false;}if(temp == a6){if(chose==true){t1.setText("");t2.setText("");} t1.setText(t1.getText()+""+"6");chose=false;}if(temp == a7){if(chose==true){t1.setText("");t2.setText("");} t1.setText(t1.getText()+""+"7");chose=false;}if(temp == a8){if(chose==true){t1.setText("");t2.setText("");} t1.setText(t1.getText()+""+"8");chose=false;}if(temp == a9){if(chose==true){t1.setText("");t2.setText("");} t1.setText(t1.getText()+""+"9");chose=false;}if(temp == a0){if(chose==true){t1.setText("");t2.setText("");} t1.setText(t1.getText()+""+"0");chose=false;}if(temp==b3){cliks=true;for(int i=0;i<t1.getText().length();i++){ if('.'==t1.getText().charAt(i)){cliks=false;break;}if(cliks==true){t1.setText(t1.getText()+".");}}}if(temp== c1){count=Double.parseDouble(t1.getText());t1.setText("");fuhao = "+";}if(temp== c2){count=Double.parseDouble(t1.getText());t1.setText("");fuhao = "-";}if(temp== c3){count=Double.parseDouble(t1.getText());t1.setText("");fuhao = "*";}if(temp== c4){count=Double.parseDouble(t1.getText());t1.setText("");fuhao = "÷";}if(temp==b1){t1.setText("");t2.setText("");}if(temp==b2){String s=t1.getText();t1.setText("");for(int i=0;i<s.length()-1;i++){char a = s.charAt(i);t1.setText(t1.getText()+a);}}if(temp== b4){count2=Double.parseDouble(t1.getText());t1.setText("");if(fuhao=="+"){//int sum=count+count2;t1.setText(count+""+fuhao+""+count2+""+"=");t2.setText(count+count2+"");chose=true;}if(fuhao=="-"){//int sum=count+count2;t1.setText(count+""+fuhao+""+count2+""+"=");t2.setText(count-count2+"");chose=true;}if(fuhao=="*"){//int sum=count+count2;t1.setText(count+""+fuhao+""+count2+""+"=");t2.setText(count*count2+"");chose=true;}if(fuhao=="÷"){//int sum=count+count2;if(count2==0){t1.setText(count+""+fuhao+""+count2+"");t2.setText("除数不能为0");return;}t1.setText(count+""+fuhao+""+count2+""+"=");t2.setText(count/count2+"");chose=true;}}}}。

java简易计算器完整代码

java简易计算器完整代码

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

java简单计算器代码

java简单计算器代码

java简单计算器代码Java简单计算器代码:```javaimport java.util.Scanner;public class Calculator {public static void main(String[] args) {Scanner input = new Scanner(System.in);double num1, num2, result = 0;char operator;System.out.print("请输入第一个数:");num1 = input.nextDouble();System.out.print("请输入运算符号(+、-、*、/):"); operator = input.next().charAt(0);System.out.print("请输入第二个数:");num2 = input.nextDouble();switch(operator) {case '+':result = num1 + num2;break;case '-':result = num1 - num2;break;case '*':result = num1 * num2;break;case '/':result = num1 / num2;break;default:System.out.println("运算符输入错误,请重新输入!");return;}System.out.println("运算结果:" + num1 + operator + num2 + "=" + result);}}```列表:1. 首先,在程序中导入`java.util.Scanner`包,以便从控制台读取用户输入内容。

Java代码实现计算器加减乘除简易功能

Java代码实现计算器加减乘除简易功能

Java代码实现计算器加减乘除简易功能package test;import javax.swing.*;import java.awt.*;import java.awt.event.KeyAdapter;import java.awt.event.KeyEvent;import java.util.HashMap;import java.util.Stack;/*** Created by zxx on 2020/10/15.*/public class Calculator extends JFrame{private Stack<Double> operandStack= new Stack<>();private Stack<String> operatorStack = new Stack<>();private Calculator(){setTitle("计算器");setSize(266,340);//setSize(400,540);Container c=getContentPane();c.setLayout(null);JTextArea jt=new JTextArea(100,100);jt.setFont(new Font("Aria",Font.BOLD,32));jt.setLineWrap(true);JScrollPane sp=new JScrollPane(jt);jt.setCaretPosition(jt.getDocument().getLength());sp.setBounds(0,0,250,100);c.add(sp);JPanel p=new JPanel();p.setLayout(new GridLayout(5,4,0,0));p.setBounds(0,100,250,200);String[] num={"(",")","AC","/","7","8","9","*","4","5","6","-","1","2","3","+","0",".","DEL","="};JButton[] jb=new JButton[20];for(int i=0;i<20;i ++ ){jb[i]=new JButton(num[i]);p.add(jb[i]);}c.add(p);for(int i=0;i<18;i ++){if(i!=2){final int j=i;jb[i].addActionListener(e-> jt.append(num[j]));}}jb[2].addActionListener(e->{jt.setText("");operandStack.clear();operatorStack.clear();});jb[18].addActionListener(e->{try{jt.setText(jt.getText().substring(0,jt.getText().length()-1));}catch(Exception ignored) { }//忽略这个异常 IDEA就是好⽤!!!});jb[19].addActionListener(e->{try{double x= calculate(jt.getText()+ "#");jt.setText("");jt.append(String.valueOf(x));}catch(Exception ex){if(ex.getMessage()==null)jt.setText("ERROR!");elsejt.setText(ex.getMessage());}});//禁⽌⽂本域的enter换⾏KeyStroke enter = KeyStroke.getKeyStroke("ENTER");jt.getInputMap().put(enter, "none");this.getRootPane().setDefaultButton(jb[19]);c.addKeyListener(new KeyAdapter() {@Overridepublic void keyTyped(KeyEvent e){}public void keyPressed(KeyEvent e) //键盘按键监听{char label=e.getKeyChar();String k=String.valueOf(label);if(label==KeyEvent.VK_ENTER){calculate();}else if(label==KeyEvent.VK_BACK_SPACE){String s = jt.getText();if(s!=null){calculate(); //调⽤定义的处理←⽅法}else{jt.setText(s);}}else{calculate(k); //按下数字和运算符号的叠加}}public void keyReleased(KeyEvent e){}});setVisible(true);setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);}private void calculate(){String b = operatorStack.pop();double c = operandStack.pop();double d = operandStack.pop();double e;if (b.equals("+")) {e = d + c;operandStack.push(e);}if (b.equals("-")) {e = d - c;operandStack.push(e);}if (b.equals("*")) {e = d * c;operandStack.push(e);}if (b.equals("/")) {if(c==0)throw new ArithmeticException("DivideByZero!");//不可修改为Exception// Exception的异常是必须处理的,是受控异常;⽽ArithmeticException 不是必须处理的 ,受控异常必须强制处理 e = d / c;operandStack.push(e);}}private Double calculate(String text){HashMap<String,Integer> precede=new HashMap<>();precede.put("(",0);precede.put(")",0);precede.put("/",2);precede.put("*",2);precede.put("-",1);precede.put("+",1);precede.put("#",0);operatorStack.push("#");int flag=0;for(int i=0;i<text.length();i++ ){String a=String.valueOf(text.charAt(i));if(!a.matches("[0-9.]")){if(flag!=i)operandStack.push(Double.parseDouble(text.substring(flag,i)));flag=i+ 1;while(!(a.equals("#")&&operatorStack.peek().equals("#"))){if(precede.get(a)>precede.get(operatorStack.peek())||a.equals("(")){ operatorStack.push(a);break;}else {if(a.equals(")")) {while(!operatorStack.peek().equals("("))calculate();operatorStack.pop();break;}calculate();}}}}return(operandStack.pop());}public static void main(String[] args){new Calculator();}}。

简单的计算器java代码

简单的计算器java代码

CalculatorCore() {
setupOperators();
setupProcessors();
}
// 为每种命令添加处理方式
private void setupProcessors() {
setupTextbox();
panel.add(textbox, BorderLayout.CENTER);
this.add(panel, BorderLayout.NORTH);
}
// 调整文本框
MyCalculator frame = new MyCalculator("我的计算器");
frame.setVisible(true); // 在桌面上显示窗体
}
}
/**
* 计算器核心逻辑。这个逻辑只能处理 1~2 个数的运算。
this.add(panel, BorderLayout.CENTER);
}
/**
* 在指定的面板上创建按钮
*
* @param panel 要创建按钮的面板
* @param labels 按钮文字
if (label.equals("")) {
panel.add(new JPanel());
JButton(label);
}
});
processors.put("\\.", new Processor() {
public void calculate(String command) {
dotClicked();
}
});
processors.put("C", new Processor() {

java简易计算机代码

java简易计算机代码

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

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

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

java简单计算器代码

java简单计算器代码

java简单计算器代码public class Calculator {public static void main(String[] args) {Calculator calculator = new Calculator(); //创建对象调⽤函数Scanner scanner = new Scanner(System.in); //创建scanner扫描对象,获取⽤户输⼊数据System.out.println("请输⼊第⼀个数据");double a=scanner.nextDouble();System.out.println("请输⼊运算符:");String operator=scanner.next();System.out.println("请输⼊第⼆个数据");double b= scanner.nextDouble();double result=0;//存储最后的计算结果scanner.close();//关闭scanner资源// 根据输⼊的运算符调⽤不同的⽅法if ("+".equals(operator)){//equals判断字符是否相等result= calculator.add(a,b);}//调⽤减法else if ("-".equals(operator)){result=calculator.sub(a,b);}else if ("*".equals(operator)){result=calculator.multiply(a,b);}else if ("/".equals(operator)){result=calculator.div(a,b);}System.out.println("最终结果为"+result);}public double add(double a,double b){return a+b;}public double sub(double a,double b){return a-b;}public double multiply(double a, double b){return a*b;}public double div(double a, double b){return a/b;}}。

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

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

相关文档
最新文档