Java简易计算器

合集下载

用Java编写一个简单的计算器

用Java编写一个简单的计算器
b3 = new JButton("MC");
b3.setForeground(Color.red);
b3.addActionListener(new button());
b4 = new JButton("MR");
b4.setForeground(Color.red);
b4.addActionListener(new button());
p4.add(tf2);
p4.setBounds(10,88,50,60);
p1.setLayout(gl1);
p1.setBounds(75, 87, 317, 35);
p2.setLayout(gl2);
p2.setBounds(10, 135, 60, 250);
p3.setLayout(gl3);
tf2 = new TextField(10);
tf2.setEditable(false);
setBackground(new Color(180,127,120));
setBounds(300, 250, 400, 400);
p0.add(tf1);
p0.setBounds(5, 50, 390,40);
gl3 = new GridLayout(4, 5, 5, 5);
tf1 = new JTextField(27);
tf1.setHorizontalAlignment(JTextField.RIGHT);
tf1.setEnabled(false);
tf1.setText("0.");
MenuItem mi1=new MenuItem("复制(C) Ctrl+C ");

java实现简单计算器

java实现简单计算器
{
@Override
public void windowClosing(WindowEvent e)
{
System.exit(-1);
}
}
);
}
}
public class Test5
{
public static void main(String[] args)
switch(str)
{
case "0":
case "1":
case "2":
case "3":
case "4":;
case "5":
case "6":
case "7":
case "8":
case "9":
if (mf.data.size()==2)
public MyActionClick1(MyFrameCal1 mf)
{
this.mf = mf;
}
@Override
public void actionPerformed(ActionEvent e)
{
String str = e.getActionCommand();
{
new MyFrameCal1().lauch();
}
}
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import javax.swing.JOptionPane;

简易计算器(java实现)

简易计算器(java实现)

//此计算器能够进行简单的加减乘除运算,界面如下:package 计算器;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.JLabel;import javax.swing.JPanel;import javax.swing.JTextArea;class Calc implements ActionListener{JFrame frame=new JFrame("计算器");JPanel pan=new JPanel(new GridLayout(4,4,20,30));JTextArea xianshi=new JTextArea(1,20);JLabel lab1=new JLabel("结果:");JButton []number=new JButton[10];JButton plus=new JButton("+");JButton reduce=new JButton("-");JButton multi=new JButton("*");JButton divide=new JButton("/");JButton point=new JButton(".");JButton equals=new JButton("=");JButton reset=new JButton("重置");float num1=0,num2=0;boolean flag=false;int t=0;int temp=0; //temp记录每次按下键的类型public void jisuan(){for(int i=0;i<=9;i++){number[i]=new JButton(Integer.toString(i));pan.add(number[i]);number[i].addActionListener(this);}pan.add(point);pan.add(equals);pan.add(plus);pan.add(reduce);pan.add(multi);pan.add(divide);lab1.setBounds(30, 10, 80, 20);xianshi.setBounds(100, 10, 200, 20);reset.setBounds(310, 10, 60, 30);pan.setBounds(10, 50, 360, 360);this.frame.setLayout(null);this.frame.add(xianshi);this.frame.add(pan);this.frame.add(lab1);this.frame.add(reset);this.frame.setBounds(400, 200, 400, 500);this.frame.setVisible(true);xianshi.setEditable(false);xianshi.setText("0");point.addActionListener(this);equals.addActionListener(this);plus.addActionListener(this);reduce.addActionListener(this);multi.addActionListener(this);divide.addActionListener(this);reset.addActionListener(new ActionListener(){ @Overridepublic void actionPerformed(ActionEvent arg0) {xianshi.setText("0");num1=num2=0;t=0;flag=false;}});}@Overridepublic void actionPerformed(ActionEvent arg0) {String n=xianshi.getText();for(int i=0;i<=9;i++){if(arg0.getSource()==number[i]){if((xianshi.getText().equals("0")&&xianshi.getText().length()==1)||temp==3)xianshi.setText(Integer.toString(i));elsexianshi.append(Integer.toString(i));flag=true;temp=1; //1表示按下数字键}}if(!flag){ //非数字键触发事件if(arg0.getSource()==point){if(xianshi.getText().matches("\\-?\\d+")||xianshi.getText().matches("\\-?\\d+(\\.+\\d+)?['+''\\-''* ''/']\\d*"))//对应num1,num2中小数xianshi.append(".");}else if(arg0.getSource()!=equals){ //键入运算符if(!n.matches("\\-?\\d+(\\.\\d+)?['+''\\-''*''/']")){try{num1=Float.parseFloat(xianshi.getText());}catch(Exception e){}if(arg0.getSource()==plus){t=1;xianshi.append("+");}else if(arg0.getSource()==reduce){if(xianshi.getText().equals("0")||temp==3)xianshi.setText("-"); //负号的显示else{t=2;xianshi.append("-");//减号}}else if(arg0.getSource()==multi){t=3;xianshi.append("*");}else if(arg0.getSource()==divide){t=4;xianshi.append("/");}temp=2; //表示按下运算符键}}else { //键入等于String tmp=xianshi.getText();int first=0;if(t==1){first=tmp.indexOf("+");num2=this.updatenum2(tmp, first);xianshi.setText(Float.toString(num1+num2));}else if(t==2){first=stIndexOf("-");num2=this.updatenum2(tmp, first);xianshi.setText(Float.toString(num1-num2));}else if(t==3){first=tmp.indexOf("*");num2=this.updatenum2(tmp, first);xianshi.setText(Float.toString(num1*num2));}else if(t==4){first=tmp.indexOf("/");num2=this.updatenum2(tmp, first);xianshi.setText(Float.toString(num1/num2));}num1=num2=Float.parseFloat(xianshi.getText());temp=3; //按下等于键t=0;}}flag=false;}public float updatenum2(String tmp,int first){if(first==tmp.length()-1)num2=num1;elsenum2=Float.parseFloat(tmp.substring(first+1));return num2;}}public class CalcDemo {public static void main(String[] args) {new Calc().jisuan();}}。

Java 简易计算器

Java 简易计算器

import java.awt.*;import java.awt.event.*;import javax.swing.*;import javax.swing.border.TitledBorder;public class calculator2 extends JFrame implements ActionListener {/****/private static final long serialV ersionUID = 1L;private boolean clickBeforeOperator; // 点击"+,-,*,/"等数学运算符和清除回车时// clickBeforeOperator = true private int firstInputChar; // 判断是否是第一次输入字符,firstInputChar = 0时是第一次输入private double answer; // 文本框中结果private int Operator;private DisplayPanel displaypanel = new DisplayPanel();private ButtonPanel buttonpanel = new ButtonPanel();private Point origin;private class DisplayPanel extends JPanel {/****/private static final long serialV ersionUID = 20120815L;private JTextField text;private JPanel del_clear = new JPanel();private JButton clear = new JButton("AC");private JButton del = new JButton("←");private TitledBorder title = new TitledBorder(null, "计算器------右键关闭", TitledBorder.DEFAULT_JUSTIFICA TION, TitledBorder.DEFAULT_POSITION, null, Color.white);public DisplayPanel() {text = new JTextField("",18);text.setBackground(Color.white); // 设置文本颜色text.setHorizontalAlignment(JTextField.RIGHT); // 设置右对齐text.setEditable(false); // 设置不可编辑del.setBackground(new Color(50, 50, 50));del.setForeground(Color.white);clear.setBackground(new Color(50, 50, 50));clear.setForeground(Color.white);del_clear.add(del);del_clear.add(clear);del_clear.setBackground(Color.black);this.setBackground(Color.black);this.setLayout(new BorderLayout()); // 面板设置为边布局this.add(text, BorderLayout.CENTER); // text文本行放在面板DisplayPanelthis.add(del_clear, BorderLayout.EAST);this.setBorder(title);}}public class ButtonPanel extends JPanel {/****/private static final long serialV ersionUID = 1L;private String button_str[] = { "7", "8", "9", "/", "4", "5", // 字符串数组"6", "*", "1", "2", "3", "-", // 做JButton的标签".", "0", "=", "+" };private JButton button[] = new JButton[button_str.length]; // 创建JButton按钮public ButtonPanel() {this.setLayout(new GridLayout(4, 4, 2, 2)); // 面板布局管理器设置为网格布局管理器this.setBackground(Color.black);for (int i = 0; i < button_str.length; i++) {button[i] = new JButton(button_str[i]);this.add(button[i]); // 在面板上添加button组件}// 设置button颜色for (int i = 0; i < button_str.length; i++) {if (i != 3 & i != 7 & i != 11 & i != 14 & i != 15) {button[i].setBackground(new Color(100, 100, 100));} else {button[i].setBackground(new Color(50, 50, 50));}button[i].setForeground(Color.white);}}}public calculator2() { // 构造方法super("计算器");try {UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());} catch (ClassNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (InstantiationException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IllegalAccessException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (UnsupportedLookAndFeelException e) {// TODO Auto-generated catch blocke.printStackTrace();}answer = 0;clickBeforeOperator = false; // 指示器firstInputChar = 0;Operator = -1;this.setBackground(Color.LIGHT_GRAY);this.setDefaultCloseOperation(EXIT_ON_CLOSE);this.getContentPane().setLayout(new BorderLayout(0, 1)); // 水平间距hgap = 0,垂直间距vgap=2this.getContentPane().setBackground(Color.black);this.getContentPane().add(displaypanel, "North"); // 框架"北"放置文本行textthis.getContentPane().add(buttonpanel, "Center"); // 框架"中"放置面板组件for (int i = 0; i < buttonpanel.button_str.length; i++) {buttonpanel.button[i].addActionListener(this);}displaypanel.del.addActionListener(this);displaypanel.clear.addActionListener(this);this.setBounds(300, 300, 250, 300);this.setResizable(false);this.setUndecorated(true);//由于隐藏了Frame边框,故一下做移动窗口和关闭的方法this.origin=new Point();addMouseListener(new MouseAdapter(){public void mousePressed(MouseEvent e){origin.x = e.getX();origin.y = e.getY();}//窗体上单击鼠标右键关闭程序public void mouseClicked(MouseEvent e) {if(e.getButton()==MouseEvent.BUTTON3)System.exit(0);}public void mouseReleased(MouseEvent e) {super.mouseReleased(e);}@Overridepublic void mouseEntered(MouseEvent e) {repaint();}});addMouseMotionListener(new MouseMotionAdapter(){public void mouseDragged(MouseEvent e){Point p = getLocation();setLocation(p.x + e.getX() - origin.x, p.y + e.getY() - origin.y );}});this.setV isible(true);}public void actionPerformed(ActionEvent e) {String button_label = e.getActionCommand();// ******************************输入double型数据********************************if ((button_label.charAt(0) >= '0' && button_label.charAt(0) <= '9')|| button_label == ".") {if (clickBeforeOperator == true || firstInputChar == 0) { // 如果点击了运算符,清除回车等按键,再点击数字键displaypanel.text.setText("" + button_label);clickBeforeOperator = false;firstInputChar = 1;} else {if (!(button_label == ".")) // 如果输入数字{displaypanel.text.setText(displaypanel.text.getText()+ button_label);}if (button_label == ".") { // 如果输入点boolean isContainerPoint = false; // 判断逻辑量if (displaypanel.text.getText().equals("")) // 如果文本行中字符串为空{isContainerPoint = true;displaypanel.text.setText("0.");}for (int i = 0; i < displaypanel.text.getText().length(); i++) // 判断文本行中字符串是否已含小数点{if (displaypanel.text.getText().charAt(i) == '.') {isContainerPoint = true;}}if (isContainerPoint == false) {displaypanel.text.setText(displaypanel.text.getText()+ ".");}}}}// **************************************清除键*************************************if (button_label == "AC") {displaypanel.text.setText("");clickBeforeOperator = true;firstInputChar = 0;}// **************************************删除*************************************try // 异常处理{if (button_label == "←") {String str = displaypanel.text.getText();displaypanel.text.setText(str.substring(0, str.length() - 1)); // 最初此语句无效????why,当把回车键标签名设置为BackSpace时,此语句失效clickBeforeOperator = true;firstInputChar = 0; // BackSpace字符串长度过长,导致界面上无法显示全部字符串,故无法实现此功能}} catch (StringIndexOutOfBoundsException sioobe) {JOptionPane.showMessageDialog(this, "已空,无法继续删除");}finally {}// ***************************************加减乘除运算*****************************************if (button_label == "+" || button_label == "-" || button_label == "*"|| button_label == "/") {if (button_label == "+") {clickBeforeOperator = true;firstInputChar = 0;answer = Double.parseDouble(displaypanel.text.getText());Operator = 0;}if (button_label == "-") {clickBeforeOperator = true;firstInputChar = 0;answer = Double.parseDouble(displaypanel.text.getText());Operator = 1;}if (button_label == "*") {clickBeforeOperator = true;firstInputChar = 0;answer = Double.parseDouble(displaypanel.text.getText());Operator = 2;}if (button_label == "/") {clickBeforeOperator = true;firstInputChar = 0;answer = Double.parseDouble(displaypanel.text.getText());Operator = 3;}}if (button_label == "=") {switch (Operator) {case 0:answer += Double.parseDouble(displaypanel.text.getText());displaypanel.text.setText("" + answer);firstInputChar = 0;break;case 1:answer -= Double.parseDouble(displaypanel.text.getText());displaypanel.text.setText("" + answer);firstInputChar = 0;break;case 2:answer *= Double.parseDouble(displaypanel.text.getText());displaypanel.text.setText("" + answer);firstInputChar = 0;break;case 3:if (Double.parseDouble(displaypanel.text.getText()) == 0) {JOptionPane.showMessageDialog(this, "除数不能为零");} else {answer /= Double.parseDouble(displaypanel.text.getText());displaypanel.text.setText("" + answer);firstInputChar = 0;}break;}}}public static void main(String args[]) {new calculator2();}}。

简易计算器(Android应用使用Java开发)

简易计算器(Android应用使用Java开发)

简易计算器(Android应用使用Java开发)随着智能手机的普及,手机应用程序也变得越来越多样化和智能化。

其中,计算器应用无疑是人们生活中最常用的一种应用之一。

本文将介绍如何使用Java开发一个简易计算器的Android应用程序。

1. 概述简易计算器是一款可以进行基本的数学计算的应用程序。

用户可以在界面上输入数字和操作符,计算器会自动根据用户的操作给出计算结果。

本应用程序采用Java语言进行开发,运行于Android操作系统。

2. 开发环境在开始开发前,我们需要搭建好Android开发环境。

首先,下载并安装Java Development Kit(JDK),确保版本为最新稳定版。

然后,下载并安装Android Studio,这是一款为Android开发而设计的集成开发环境(IDE)。

3. 创建项目打开Android Studio,并点击"Start a new Android Studio project"来创建一个新的项目。

在弹出的窗口中,填写项目名称、包名等基本信息,并选择适当的设备和目标SDK版本。

4. 设计界面在项目创建完成后,我们需要设计计算器的界面。

可以使用Android Studio自带的可视化UI设计器来拖拽和放置UI元素,也可以手动在XML布局文件中编写界面代码。

界面的核心组件包括输入框、按钮和显示区域。

5. 添加逻辑功能界面设计完成后,我们需要为计算器添加逻辑功能。

创建一个Java类作为计算器的主活动(Activity),在其中实现输入和操作的处理逻辑。

可以使用Android提供的计算相关API,例如使用eval()方法进行表达式计算。

6. 编译和调试在开发过程中,我们可以随时进行编译和调试来检查应用程序的运行情况。

点击Android Studio的运行按钮,选择目标设备并运行应用程序。

在模拟器或真机上进行调试,查看是否符合我们的预期效果。

7. 测试和发布在功能开发和调试完毕后,我们需要进行应用的测试阶段。

用Java设计简易的计算器

用Java设计简易的计算器

⽤Java设计简易的计算器运⾏初始状态:计算结果如下:代码如下:package jisuanqi;import java.awt.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import javax.swing.JButton;import javax.swing.JComboBox;import javax.swing.JFrame;class counter1 extends JFrame{public counter1(){super("计算器");this.setSize(400,100);this.setLocation(300,240);this.setLayout(new FlowLayout()); //确定窗⼝格式为流输⼊TextField text1=new TextField(4);text1.setText("1");this.add(text1);String proList[] = { "+","-","x" ,"%"}; //将"+","-","x" ,"%"作为列表元素TextField text;JComboBox comboBox; //创建下拉复选框Container conPane = getContentPane(); //创建⼀个名为conPane的容器comboBox = new JComboBox(proList); //把列表元素加⼊下拉复选框comboBox.setEditable(true); //使复选框变为可操作conPane.add(comboBox); //将复选框加⼊容器中TextField text2=new TextField(4);text2.setText("1");this.add(text2);JButton button = new JButton("=");this.add(button);TextField text3=new TextField(4);text3.setText("2");button.addActionListener(new ActionListener(){ //添加按钮监听事件public void actionPerformed(ActionEvent e) //创建事件响应函数{String s=comboBox.getEditor().getItem().toString(); //获取复选框中的元素double a= Integer.parseInt(text1.getText()); //将两个⽂本框中的字符串强制转换成浮点型,以便于之后的计算double b= Integer.parseInt(text2.getText());if(s.equals("+")) { //判断复选框中的元素种类double t=a+b;String m=String.valueOf(t); //由于⽂本框中的数据流只能为字符串,这⾥就需要将计算得到的浮点型数据强制转换成字符串型 text3.setText(m); //将最后的结果放在⽂本框中}else if(s.equals("-")) //后⾯的与之前的类似,不在注释else if(s.equals("-")) //后⾯的与之前的类似,不在注释{double t=a-b;String m=String.valueOf(t);text3.setText(m);}else if(s.equals("x")){double t=a*b;String m=String.valueOf(t);text3.setText(m);}else{double t=a/b;String m=String.valueOf(t);text3.setText(m);}}});conPane.add(text3);this.setVisible(true); //将窗⼝设置为可视化}}public class Counter {public static void main(String[] args){new counter1();}}修改版如下:源码如下:package jisuanqi;import java.awt.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.FocusEvent;import java.awt.event.FocusListener;import javax.swing.JButton;import javax.swing.JComboBox;import javax.swing.JFrame;import javax.swing.JLabel;class counter1 extends JFrame{public counter1(){super("计算器");this.setSize(400,130);this.setLocation(300,240);this.setLayout(new FlowLayout()); //确定窗⼝格式为流输⼊ TextField text1=new TextField(4);TextField text1=new TextField(4);text1.setText("1");JLabel label1 = new JLabel("");text1.addFocusListener(new FocusListener() { //添加焦点事件监听器public void focusGained(FocusEvent arg0) { //设置获得焦点时的事件label1.setText("正在输⼊中...");}public void focusLost(FocusEvent arg0) { //设置失去焦点时的事件if(!text1.getText().matches("\\d+")) //使⽤正则表达式判断该字符串是否为数字,第⼀个\是转义符,\d+表⽰匹配1个或 //多个连续数字,"+"和"*"类似,"*"表⽰0个或多个 label1.setText("输⼊的第⼀个数据有误");else label1.setText("");}});this.add(text1);String proList[] = { "+","-","x" ,"%"}; //将"+","-","x" ,"%"作为列表元素TextField text;JComboBox comboBox; //创建下拉复选框Container conPane = getContentPane(); //创建⼀个名为conPane的容器comboBox = new JComboBox(proList); //把列表元素加⼊下拉复选框comboBox.setEditable(true); //使复选框变为可操作conPane.add(comboBox); //将复选框加⼊容器中TextField text2=new TextField(4);text2.setText("1");this.add(text2);text2.addFocusListener(new FocusListener() {public void focusGained(FocusEvent arg0) {label1.setText("正在输⼊中...");}public void focusLost(FocusEvent arg0) {if(!text2.getText().matches("\\d+"))label1.setText("输⼊的第⼆个数据有误");else label1.setText("");}});JButton button = new JButton("=");this.add(button);TextField text3=new TextField(4);text3.setText("2");button.addActionListener(new ActionListener(){ //添加按钮监听事件public void actionPerformed(ActionEvent e) //创建事件响应函数{String s=comboBox.getEditor().getItem().toString(); //获取复选框中的元素double a= Integer.parseInt(text1.getText()); //将两个⽂本框中的字符串强制转换成浮点型,以便于之后的计算double b= Integer.parseInt(text2.getText());if(s.equals("+")) { //判断复选框中的元素种类double t=a+b;String m=String.valueOf(t); //由于⽂本框中的数据流只能为字符串,这⾥就需要将计算得到的浮点型数据强制转换成字符串型text3.setText(m); //将最后的结果放在⽂本框中}else if(s.equals("-")) //后⾯的与之前的类似,不在注释{double t=a-b;String m=String.valueOf(t);text3.setText(m);}else if(s.equals("x")){double t=a*b;String m=String.valueOf(t);text3.setText(m);}else{double t=a/b;String m=String.valueOf(t);text3.setText(m);}}});conPane.add(text3);this.add(label1);this.setVisible(true); //将窗⼝设置为可视化}}public class Counter {public static void main(String[] args){new counter1();}}总结⼼得:(1)在创建选项框时,要将所有的选项放在⼀个“容器”⾥,并把这个容器添加到程序中,这⾥我⽤的容器为JComboBox comboBox,同时需要导⼊包boBoxEditor和javax.swing.JComboBox;(2)由于设置了按钮响应功能,所以要设置按键动作和响应,这⾥导⼊了包java.awt.event.ActionEvent和java.awt.event.ActionListener(3)因为⽂本框中输⼊读取到的是字符串,所以要进⾏计算时,要先将其转为整形,在⽂本框输出时,同理要将整形转换为字符串(4)注意:当光标移动到⽂本框上⾯时,获得焦点事件,当光标移⾛时,便失去焦点事件,所以要注意两个函数的作⽤。

java实现简单的计算器

java实现简单的计算器

j a v a实现简单的计算器(共19页)--本页仅作为文档封面,使用时请直接删除即可----内页可以根据需求调整合适字体及大小--目录目录................................................................................................................. 错误!未定义书签。

1 需求分析................................................................................................... 错误!未定义书签。

计算器的基本功能:............................................................... 错误!未定义书签。

加法运算:用数字按钮和“+”按钮进行运算; ......... 错误!未定义书签。

减法运算:用数字按钮和“-”按钮进行运算;.......... 错误!未定义书签。

乘法运算:用数字按钮和“*”按钮进行运算; ......... 错误!未定义书签。

除法运算:用数字按钮和“/”按钮进行运算;.......... 错误!未定义书签。

退格键和清零键: 用”Backspace”、”C”和”CE”按钮实现; ...... 错误!未定义书签。

计算器的科学计算方法:....................................................... 错误!未定义书签。

开方:用数字按钮和“Sqrt”按钮进行运算; ............ 错误!未定义书签。

百分比:用数字按钮和“%”按钮进行运算; ............ 错误!未定义书签。

求倒数:用数字按钮和“1/x”按钮进行运算; .......... 错误!未定义书签。

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不久尝试着做了⼀个简单的计算器接下来讲讲我的思路1.创建⼀个main函数public static void main(String[] args){}2.创建对象调⽤函数public static void main(String[] args){Demo06 demo06 = new Demo06();//创建对象调⽤函数}3.创建scanner函数获取⽤户的数据public static void main(String[] args){Demo06 demo06 = new Demo06();//创建对象调⽤函数Scanner scanner = new Scanner(System.in);//scanner创建,获取⽤户数据}4.输⼊第⼀个值public static void main(String[] args){Demo06 demo06 = new Demo06();//创建对象调⽤函数Scanner scanner = new Scanner(System.in);//scanner创建,获取⽤户数据System.out.println("请输⼊⼀个值");}5.double 数据定义⽤⽤nextdouble 接受double的第⼀个数据public static void main(String[] args){Demo06 demo06 = new Demo06();//创建对象调⽤函数Scanner scanner = new Scanner(System.in);//scanner创建,获取⽤户数据System.out.println("请输⼊⼀个值");double a = scanner.nextDouble();//接受double类型的数据}6.注意这⾥可以分解,可以再输出⼀个运算符,为了清楚可以这么写,但没必要,string定义符号是字符型接受⽤next // System.out.println("请输⼊运算符:");String operator = scanner.next();//接收字符串数据注意:这边说下之前next 和nextline 区别 next 是不能够空格的,就算空格也只能够取前⾯的,⽽ nextline 可以把空格后⾯的都能够取到7.double 数据定义⽤ nextdouble 接受double的第⼆个数据// System.out.println("请输⼊⼀个数");double b = scanner.nextDouble();//接受double类型的数据注意:这边也是⼀样可以再写⼀个输出8.⽤double类型来定义结果 resultdouble result = 0;9.接下来要写外部的⽅法了,分别定义加减乘余,并返回⽅法public static double add(double a,double b){return a+b;}//加法public static double minus(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 double remainder(double a,double b){return a%b;}//余10.回到主函数分别来调⽤外⾯的⽅法,这⾥⽤if else if 来判断是否输⼊的⽅法等等于当前的符号if ("+".equals(operator)){//如果输⼊的运算符等于加号就进来result = add(a,b);//结果,调⽤加}else if("-".equals(operator)){result = minus(a,b);//结果,调⽤减}else if("*".equals(operator)){result = multiply(a,b);//结果,调⽤乘}else if("/".equals(operator)){result = divide(a,b);//结果,调⽤除}else if("%".equals(operator)){result = remainder(a,b);//结果,调⽤余}注意:"-".equals(operator), "".equals()这个⽅式是字符串的== ,⽤来判断字符串的相等的,切记不能够⽤==,会报错11.最后输出结果System.out.println("结果:"+result);12.奉上完整的代码package com.lx.method;import java.util.Scanner;public class Demo06 {//做⼀个简单的计算器public static double add(double a,double b){return a+b;}//加法public static double minus(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 double remainder(double a,double b){return a%b;}//余public static void main(String[] args) {Demo06 demo06 = new Demo06();//创建对象调⽤函数Scanner scanner = new Scanner(System.in);//scanner创建,获取⽤户数据System.out.println("请输⼊⼀个值");double a = scanner.nextDouble();//接受double类型的数据// System.out.println("请输⼊运算符:");String operator = scanner.next();//接收字符串数据// System.out.println("请输⼊⼀个数");double b = scanner.nextDouble();//接受double类型的数据double result = 0;if ("+".equals(operator)){//如果输⼊的运算符等于加号就进来result = add(a,b);}else if("-".equals(operator)){result = minus(a,b);}else if("*".equals(operator)){result = multiply(a,b);}else if("/".equals(operator)){result = divide(a,b);}else if("%".equals(operator)){result = remainder(a,b);}System.out.println("结果:"+result);}}结果:莫%运算在上⾯结果中我就在来说下% 运算吧,从刚刚结果看来我们得出以下⼏个要点1. 如果 a % b , a>b ,那么外⾯就拿a除以b余下来的值,我们拿余下来的数20 %11 = 92. 如果a % b , a=b ,那么等于b 相除下来余数就是0 ,我们就拿 020 % 10 = 03. 如果 a % b , a<b , 那么我们就拿a的⾃⼰20 % 1000 = 20。

java实现简单计算器功能

java实现简单计算器功能

java实现简单计算器功能童鞋们,是不是有使⽤计算器的时候,还要进⼊运⾏,输⼊calc,太⿇烦了,有时候甚⾄还忘记单词怎么拼写,呵呵程序员⾃⼰写代码实现,⼜简单,⼜⽅便啊以下为代码(想要⽣成可执⾏⼯具可参考:)package com;import java.awt.BorderLayout;import java.awt.EventQueue;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.JPanel;import javax.swing.JTextField;import javax.swing.SwingConstants;import javax.swing.UIManager;import javax.swing.border.EmptyBorder;public class Test extends JFrame{/*** humphrey*/private static final long serialVersionUID = -9075562467166618473L;private JPanel contentPane;private JTextField display;private ActionListener insert = new InsertAction();private ActionListener command = new CommandAction();private double result = 0;private String lastCommand = "=";private boolean start = true;/*** Launch the application.*/public static void main(String[] args) {try {UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");} catch (Throwable e) {e.printStackTrace();}EventQueue.invokeLater(new Runnable() {public void run() {try {Test frame = new Test();frame.setVisible(true);} catch (Exception e) {e.printStackTrace();}}});}/*** Create the frame.*/public Test() {setTitle("\u8BA1\u7B97\u5668");setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationByPlatform(true);contentPane = new JPanel();contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));contentPane.setLayout(new BorderLayout(0, 0));setContentPane(contentPane);JPanel displayPanel = new JPanel();contentPane.add(displayPanel, BorderLayout.NORTH);display = new JTextField();display.setText("0");display.setHorizontalAlignment(SwingConstants.RIGHT); display.setEditable(false);display.setFont(new Font("微软雅⿊", Font.PLAIN, 15)); displayPanel.add(display);display.setColumns(13);JPanel buttonPanel = new JPanel();contentPane.add(buttonPanel, BorderLayout.CENTER);buttonPanel.setLayout(new GridLayout(4, 4, 5, 5));JButton number7Button = new JButton("7");number7Button.addActionListener(insert);number7Button.setFont(new Font("微软雅⿊", Font.PLAIN, 15)); buttonPanel.add(number7Button);JButton number8Button = new JButton("8");number8Button.addActionListener(insert);number8Button.setFont(new Font("微软雅⿊", Font.PLAIN, 15)); buttonPanel.add(number8Button);JButton number9Button = new JButton("9");number9Button.addActionListener(insert);number9Button.setFont(new Font("微软雅⿊", Font.PLAIN, 15)); buttonPanel.add(number9Button);JButton divideButton = new JButton("/");divideButton.addActionListener(command);divideButton.setFont(new Font("微软雅⿊", Font.PLAIN, 15)); buttonPanel.add(divideButton);JButton number4Button = new JButton("4");number4Button.addActionListener(insert);number4Button.setFont(new Font("微软雅⿊", Font.PLAIN, 15)); buttonPanel.add(number4Button);JButton number5Button = new JButton("5");number5Button.addActionListener(insert);number5Button.setFont(new Font("微软雅⿊", Font.PLAIN, 15)); buttonPanel.add(number5Button);JButton number6Button = new JButton("6");number6Button.addActionListener(insert);number6Button.setFont(new Font("微软雅⿊", Font.PLAIN, 15)); buttonPanel.add(number6Button);JButton multiplyButton = new JButton("*");multiplyButton.addActionListener(command);multiplyButton.setFont(new Font("微软雅⿊", Font.PLAIN, 15)); buttonPanel.add(multiplyButton);JButton number3Button = new JButton("1");number3Button.addActionListener(insert);number3Button.setFont(new Font("微软雅⿊", Font.PLAIN, 15)); buttonPanel.add(number3Button);JButton number2Button = new JButton("2");number2Button.addActionListener(insert);number2Button.setFont(new Font("微软雅⿊", Font.PLAIN, 15)); buttonPanel.add(number2Button);JButton number1Button = new JButton("3");number1Button.addActionListener(insert);number1Button.setFont(new Font("微软雅⿊", Font.PLAIN, 15)); buttonPanel.add(number1Button);JButton subtractButton = new JButton("-");subtractButton.addActionListener(command);subtractButton.setFont(new Font("微软雅⿊", Font.PLAIN, 15)); buttonPanel.add(subtractButton);JButton number0Button = new JButton("0");number0Button.addActionListener(insert);number0Button.setFont(new Font("微软雅⿊", Font.PLAIN, 15)); buttonPanel.add(number0Button);JButton dotButton = new JButton(".");dotButton.setFont(new Font("微软雅⿊", Font.PLAIN, 15)); buttonPanel.add(dotButton);JButton equalButton = new JButton("=");equalButton.addActionListener(command);equalButton.setFont(new Font("微软雅⿊", Font.PLAIN, 15)); buttonPanel.add(equalButton);JButton addButton = new JButton("+");addButton.addActionListener(command);addButton.setFont(new Font("微软雅⿊", Font.PLAIN, 15)); buttonPanel.add(addButton);pack();}private class InsertAction implements ActionListener {public void actionPerformed(ActionEvent e) {String input = e.getActionCommand();String text = display.getText();if (start) {display.setText("");start = false;}if (text.startsWith(".")) {display.setText("0" + display.getText() + input);} else if (text.startsWith("-0.") || text.startsWith("0.")) {display.setText(display.getText() + input);} else if (text.startsWith("-0")) {display.setText("-" + input);} else if (text.startsWith("0")) {display.setText(input);} else {display.setText(display.getText() + input);}}}private class CommandAction implements ActionListener {public void actionPerformed(ActionEvent e) {String command = e.getActionCommand();if (start) {if (command.equals("-")) {display.setText(command);start = false;} else {lastCommand = command;}} else {calculate(Double.parseDouble(display.getText())); lastCommand = command;start = true;}}}public void calculate(double x) {char operator = lastCommand.charAt(0);switch (operator) {case '+':result += x;break;case '-':result -= x;break;case '*':result *= x;break;case '/':result /= x;break;case '=':result = x;break;}display.setText("" + result); }}。

Java实现简单的计算器

Java实现简单的计算器

安庆师范学院1.J ava实现简单的计算器。

2.编写环境 eclipse 。

3.主类在这里我命名为 xitisix 因为是我们书上的习题。

4.如果只要实现简单计算有些东西是不需要的可以自行删除,这希望对初学者有帮助。

5.实验截图。

6.实验源代码。

import java.awt.*;import java.awt.event.*;import javax.swing.*;import ng.*;public class xitisix extends JFrame { double p1;char c;int flag ;JMenuBar jb = new JMenuBar(); //菜单栏JMenu jm; //菜单JMenuItem ji,ji2; //菜单项JTextField jt = new JTextField(16); //文本框JPanel p = new JPanel(); //面板JPanel jp = new JPanel();JButton b1 = new JButton("1"), //按钮b2 = new JButton("2"),b3 = new JButton("3"),b4 = new JButton("4"),b5 = new JButton("5"),b6 = new JButton("6"),b7 = new JButton("7"),b8 = new JButton("8"),b9 = new JButton("9"),b0 = new JButton("0"),b11 = new JButton("+"),b12 = new JButton("-"),b13 = new JButton("*"),b14 = new JButton("/"),b15 = new JButton("."),b16 = new JButton("="),b17 = new JButton("c"), //清除文本的数据b18 = new JButton("p"),//平方运算b19 = new JButton("s"), //开方运算b20 = new JButton("e"); //e的指数运算public xitisix(){setJMenuBar(jb); //添加菜单jb.add(jm = new JMenu("帮助"));jm.add(ji = new JMenuItem("关于"));jm.add(ji2 = new JMenuItem("退出"));setTitle("计算器");p.setLayout(new GridLayout(5,4,5,7));//添加按钮p.add(b17);p.add(b18);p.add(b19);p.add(b20);p.add(b7);p.add(b8);p.add(b9);p.add(b14);p.add(b4);p.add(b5);p.add(b6);p.add(b13);p.add(b1);p.add(b2);p.add(b3);p.a dd(b12);p.add(b0);p.add(b15);p.add(b16);p.add(b11);jp.add(jt);add(p,BorderLayout.CENTER);add(jp,BorderLayout.NORTH);ji.addActionListener(new ML()); //注册监听器ji2.addActionListener(new ML());b0.addActionListener(new ML());b1.addActionListener(new ML());b2.addActionListener(new ML());b3.addActionListener(new ML());b4.addActionListener(new ML());b5.addActionListener(new ML());b6.addActionListener(new ML());b7.addActionListener(new ML());b8.addActionListener(new ML());b9.addActionListener(new ML());b11.addActionListener(new ML());b12.addActionListener(new ML());b14.addActionListener(new ML());b15.addActionListener(new ML());b16.addActionListener(new ML());b13.addActionListener(new ML());b17.addActionListener(new ML());b18.addActionListener(new ML());b19.addActionListener(new ML());b20.addActionListener(new ML());jt.setEditable(false);jt.setHorizontalAlignment(JTextField.RIGHT);setSize(200,260);//设置窗口大小setVisible(true);setResizable(false);setLocation(560,280);setDefaultCloseOperation(JFrame.EXIT_ON_CLOS E);}class ML implements ActionListener{ //内部类public void actionPerformed(ActionEvent e){ String s = e.getActionCommand();if(s.equals("关于")){JOptionPane.showMessageDialog(xitisix.this,"安庆师范学院","关于",RMATION_MESSAGE);}if(s.equals("退出")){System.exit(0);}if((JButton)e.getSource() == b17){jt.setText("");}if((JButton)e.getSource() == b18){act1(0);double b =Double.parseDouble(jt.getText().trim());double c = Math.pow(b,2);jt.setText(String.valueOf(c));}if((JButton)e.getSource() == b19){act1(0);double b =Double.parseDouble(jt.getText().trim());double c = Math.pow(b,0.5);jt.setText(String.valueOf(c));}if((JButton)e.getSource() == b20){ act1(0);double b =Double.parseDouble(jt.getText().trim());double c = Math.exp(b);jt.setText(String.valueOf(c));}if((JButton)e.getSource() == b1){if(act2() == 0){jt.setText("");}act1(1);String a = jt.getText().trim();String b = a + "1";jt.setText(b);}if((JButton)e.getSource() == b2){if(act2() == 0){jt.setText("");}act1(1);String a = jt.getText().trim();String b = a + "2";jt.setText(b);}if((JButton)e.getSource() == b3){ if(act2() == 0){jt.setText("");}act1(1);String a = jt.getText().trim();String b = a + "3";jt.setText(b);}if((JButton)e.getSource() == b4){ if(act2() == 0){jt.setText("");}act1(1);String a = jt.getText().trim();String b = a + "4";jt.setText(b);}if((JButton)e.getSource() == b5){ if(act2() == 0){jt.setText("");}act1(1);String a = jt.getText().trim();String b = a + "5";jt.setText(b);}if((JButton)e.getSource() == b6){ if(act2() == 0){jt.setText("");}act1(1);String a = jt.getText().trim();String b = a + "6";jt.setText(b);}if((JButton)e.getSource() == b7){ if(act2() == 0){jt.setText("");}act1(1);String a = jt.getText().trim();String b = a + "7";jt.setText(b);}if((JButton)e.getSource() == b8){ if(act2() == 0){jt.setText("");}act1(1);String a = jt.getText().trim();String b = a + "8";jt.setText(b);}if((JButton)e.getSource() == b9){ if(act2() == 0){jt.setText("");}act1(1);String a = jt.getText().trim();String b = a + "9";jt.setText(b);}if((JButton)e.getSource() == b0){ if(act2() == 0){jt.setText("");}act1(1);String a = jt.getText().trim();String b = a + "0";jt.setText(b);}if((JButton)e.getSource() == b15){ if(act2() == 0){jt.setText("");}act1(1);String a = jt.getText().trim();String b = a + ".";jt.setText(b);}if((JButton)e.getSource() == b11){ calculate1('+');calculate2();}if((JButton)e.getSource() == b12){ calculate1('-');calculate2();}if((JButton)e.getSource() == b13){ calculate1('*');calculate2();}if((JButton)e.getSource() == b14){ calculate1('/');calculate2();}if((JButton)e.getSource() == b16){calculate();}}}public void calculate1(char q){//获取文本框中的数据,传递运算符号p1 =Double.parseDouble(jt.getText().trim());c = q;}public void calculate2(){ // jt.setText("");}public double cal1(){ //标记是否一次运算结束了,为0时结束return p1;}public char cal2(){return c;}public void act1(int f){flag = f;}public int act2(){return flag;}public void calculate(){ //实现运算char o = cal2();switch(o){case'+':double n1 =Double.parseDouble(jt.getText().trim());double m1 = cal1() + n1;jt.setText(String.valueOf(m1));act1(0);break;case'-':double n2 =Double.parseDouble(jt.getText().trim());double m2 = cal1() - n2;jt.setText(String.valueOf(m2));act1(0);break;case'*':double n3 =Double.parseDouble(jt.getText().trim());double m3 = cal1() * n3;jt.setText(String.valueOf(m3));act1(0);break;case'/':double n4 =Double.parseDouble(jt.getText().trim());double m4 = cal1() / n4;jt.setText(String.valueOf(m4));act1(0);break;}}public static void main(String[] args){ xitisix xiti = new xitisix();}}。

Java实现一个简易计算器

Java实现一个简易计算器

Java实现⼀个简易计算器做⼀个多功能计算器 ====== 欢迎使⽤计算器系统 ========1. int + int2. double + double 、3. 计算 n 的阶乘4. 计算 a的 n次⽅、5. 退出系统、import java.util.Scanner;public class Calculator {public static void main(String[] args) {//计算器界⾯calInter();Scanner sc = new Scanner(System.in);System.out.println("请输⼊功能选项:");int i = sc.nextInt();int j = 1;while(true){switch (i){case 1:System.out.println("结果为:"+addInt());break;case 2:System.out.println("结果为:"+addDouble());break;case 3:System.out.println("结果为:"+factor());break;case 4:System.out.println("结果为:"+power());break;case 5:exit();j = 0;break;default:System.out.println("输⼊功能选项有误,您只能选择1~5之间的整数,请重新输⼊!");}if(j == 0){break;}System.out.println("请输⼊功能选项:");i = sc.nextInt();}}//计算器界⾯public static void calInter(){System.out.println("====== 欢迎使⽤计算器系统 ========");System.out.println("1. int + int");System.out.println("2. double + double ");System.out.println("3. 计算 n 的阶乘");System.out.println("4. 计算 a的 n次⽅");System.out.println("5. 退出系统");}//Int加法public static int addInt(){Scanner sc = new Scanner(System.in);System.out.println("第⼀个int数为:");int a = sc.nextInt();System.out.println("第⼆个int数为:");int b = sc.nextInt();return a + b;}//double加法public static double addDouble(){Scanner sc = new Scanner(System.in);System.out.println("第⼀个double数为:");double a = sc.nextDouble();System.out.println("第⼆个数double为:");double b = sc.nextDouble();return a + b;}//n的阶乘public static int factor(){Scanner sc = new Scanner(System.in);System.out.println("阶乘n为:");int n = sc.nextInt();int fact = 1;for(int i = 1; i <= n ;i++){fact *= i;}return fact;}//a的n次⽅public static double power(){Scanner sc = new Scanner(System.in); System.out.println("底数a为:");int a = sc.nextInt();System.out.println("幂数n为:");int n = sc.nextInt();return Math.pow(a,n);}//退出系统public static void exit(){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实现简单计算器界面设计:用一个JPanel1 布局是网格(4*4),分别放置数字和功能键,再用一个JPanel2 放置显示区(JTextArea)1和2,在把JPanel1放入JPanel2中,JPanel2 放入JFrame中;计算:有数字按钮按下时,把相应的值读入显示区里,当有功能键按下时,显示区清空,在读入第二操作数,当有”=”按下时,调用相应的函数计算结果,并显示。

并激活相应的监听器。

源程序:import java.awt.*;import javax.swing.*;import java.awt.event.*;public class MyCal1 {public static void main(String[] args){new ClaJFrame();}}class ClaJFrame extends JFrame{//计算器窗口public ClaJFrame(){super("计算器1");this.setBounds(500, 500, 200, 200);this.setDefaultCloseOperation(EXIT_ON_CLOSE);this.getContentPane().add(new NumJPanel());this.setVisible(true);}}class NumJPanel extends JPanel{String op;//保存操作符String op1,op2;//读取操作数JButton []JBut_Num=new JButton[10];JButton jbt_add;//功能键+JButton jbt_sub;//功能键-JButton jbt_cheng;//功能键*JButton jbt_chu;//功能键/JButton jbt_eq;//功能键=JButton jbt_c;//功能键清0JTextArea JPText;//显示区1JTextArea JPText1;//显示区2JPanel JPCal=new JPanel();public NumJPanel(){//JPanel 放置0~9数字按键和+ 、-、*、/功能键JPText1=new JTextArea(1,15);//过程记录JPText1.setEditable(false);this.add(JPText1);JPText=new JTextArea(1,15);//结果和输入区this.add(JPText);for(int i=0;i<10;i++){//添加0~9数字按键JBut_Num[i]=new JButton(new Integer(i).toString());JPCal.add(JBut_Num[i]);JBut_Num[i].addActionListener(new BT_Action());//注册数字按键监听}JPCal.setLayout(new GridLayout(4,4,0,0));jbt_add=new JButton("+");jbt_add.addActionListener(new Op_Action());//注册功能按键监听JPCal.add(jbt_add);jbt_sub=new JButton("-");jbt_sub.addActionListener(new Op_Action());JPCal.add(jbt_sub);jbt_cheng=new JButton("*");jbt_cheng.addActionListener(new Op_Action());JPCal.add(jbt_cheng);jbt_chu=new JButton("/");jbt_chu.addActionListener(new Op_Action());JPCal.add(jbt_chu);jbt_eq=new JButton("=");jbt_eq.addActionListener(new Op_Action());JPCal.add(jbt_eq);jbt_c=new JButton("C");jbt_c.addActionListener(new Op_Action());JPCal.add(jbt_c);this.add(JPCal);}class BT_Action implements ActionListener {//实现数字按键监听器接口public void actionPerformed( ActionEvent e ) {JPText.append(e.getActionCommand());JPText1.append(e.getActionCommand());}}class Op_Action implements ActionListener,Result {//实现数字按键监听器接口public void actionPerformed( ActionEvent e ) {JPText1.append(e.getActionCommand());if(e.getActionCommand().equals("-")||e.getActionCommand().equals("+")||e.getActionCommand().equals("*")||e.getActionCommand().equals("/")){op1=JPText.getText().trim();op=e.getActionCommand();JPText.setText("");}if(e.getSource()==jbt_eq){CaL_tor(op);}if(e.getSource()==jbt_c){JPText.setText("");JPText1.setText("");}}public void CaL_tor(String str){if(str=="-"){op2=JPText.getText().trim();JPText.setText(""+Sub(op1,op2));}if(str=="+"){op2=JPText.getText().trim();JPText.setText(""+Add(op1,op2));}if(str=="*"){op2=JPText.getText().trim();JPText.setText(""+Mul(op1,op2));}if(str=="/"){try{op2=JPText.getText().trim();JPText.setText(""+Div(op1,op2));}catch(ArithmeticException e){JFrame JD;JD=new JFrame();JD.setBounds(550,500,100,80);JD.add(new JLabel("除数不能为0!"));JD.setVisible(true);}}}public int Sub(String str1,String str2){return (Integer.parseInt(str1))-(Integer.parseInt(str2));}public int Add(String str1,String str2){return (Integer.parseInt(str1))+(Integer.parseInt(str2));}public int Div(String str1,String str2){return (Integer.parseInt(str1))/(Integer.parseInt(str2));}public int Mul(String str1,String str2){return (Integer.parseInt(str1))*(Integer.parseInt(str2));}}}interface Result {//计算功能接口public abstract int Add(String str1,String str2);public abstract int Sub(String str1,String str2);public abstract int Mul(String str1,String str2);public abstract int Div(String str1,String str2);}运行结果:。

java简易计算器完整代码

java简易计算器完整代码

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

java简易计算器设计思路

java简易计算器设计思路

java简易计算器设计思路Java简易计算器设计思路一、引言计算器是我们日常生活中常用的工具之一,可以帮助我们进行各种简单的数学计算。

本文将介绍如何使用Java编程语言设计一个简易的计算器。

二、功能需求我们的计算器需要具备以下基本功能:1. 实现加、减、乘、除四则运算;2. 能够处理小数、整数和负数的运算;3. 具备清除操作,清零当前计算结果;4. 能够处理连续计算,即进行多次连续的运算。

三、设计思路在设计简易计算器时,我们可以考虑以下步骤:1. 用户界面设计首先,我们需要设计一个用户界面,让用户能够输入数字和选择运算符号。

可以使用Java的Swing或JavaFX进行界面设计。

2. 输入数字和运算符在用户界面中,我们可以使用文本框和按钮来实现数字的输入和运算符的选择。

用户在文本框中输入数字,然后点击相应的按钮选择运算符号。

3. 运算处理根据用户的选择,我们可以利用Java中的if或switch语句来进行相应的运算处理。

比如用户选择加法运算,则获取用户输入的两个数字并相加。

同样,对于减法、乘法和除法运算,我们也可以使用相应的语句进行处理。

4. 显示结果最后,我们需要将计算结果显示在用户界面的文本框中。

将处理后的结果显示在界面上,让用户直观地看到计算结果。

5. 清除操作我们还可以添加一个清除按钮,使用户能够清除当前的计算结果,重新进行新的计算。

四、扩展功能除了基本的计算功能外,我们还可以考虑增加以下扩展功能:1. 添加括号功能,使计算器能够处理复杂的表达式;2. 添加开平方、取余、求幂等高级运算;3. 添加历史记录功能,保存用户之前的计算结果;4. 添加单位转换功能,使计算器能够进行长度、重量、温度等单位之间的转换。

五、总结通过以上设计思路,我们可以实现一个简易的计算器,满足用户的基本计算需求。

同时,我们可以根据实际需求添加扩展功能,提升计算器的实用性和灵活性。

希望本文对您设计和实现一个Java简易计算器有所帮助。

java实现简单的计算器(word文档良心出品)

java实现简单的计算器(word文档良心出品)

目录目录 (I)1需求分析 (1)1.1计算器的基本功能: (1)1.1.1加法运算:用数字按钮和“+”按钮进行运算; (1)1.1.2减法运算:用数字按钮和“-”按钮进行运算; (1)1.1.3乘法运算:用数字按钮和“*”按钮进行运算; (1)1.1.4除法运算:用数字按钮和“/”按钮进行运算; (1)1.2退格键和清零键: 用”Backspace”、”C”和”CE”按钮实现; (1)1.3计算器的科学计算方法: (1)1.3.1开方:用数字按钮和“Sqrt”按钮进行运算; (1)1.3.2百分比:用数字按钮和“%”按钮进行运算; (1)1.3.3求倒数:用数字按钮和“1/x”按钮进行运算; (1)1.3.4求自然对数:用数字按钮和“ln”按钮进行运算; (1)1.3.5三角函数:用数字按钮和“tan”“cos”“sin”按钮进行运算 (1)1.3.6角度换算成弧度:用数字按钮和“’ ””按钮进行运算 (1)1.3.7求反:用数字按钮和“-/+”按钮进行运算 (1)1.3.8平方和三次方:用数字按钮和“x^2”“x^3”按钮进行运算 (1)1.4常数: (2)1.4.1π:用Math类中的PI来实现 (2)1.4.2自然对数e:用Math类中的E来实现 (2)2设计 (2)2.1用户界面设计 (2)2.1.1该计算器程序的设计:用户界面包括Swing组件,不过程序中大都使用的是AWT组件. (2)2.1.2在AWT组件, (2)2.1.3这个界面设计中包含了五个接口,分别控制运算符,数字,清除,存储功能和小数点的输入 (2)2.1.4程序设计中,使用了布局管理: (3)2.2概要设计 (3)2.2.1它的功能是使用图形用户来实现计算器的界面设计和运算功能以及一些科学运算方法. (3)3实现 (3)4测试 (14)4.1实现加法运算:4+12=16 (14)4.2实现乘法运算:3*9=27 (15)4.3用”C’实现清零功能: (16)4.4用”Backspace”实现退格功能: (17)4.5求倒数:1/4=0.25 (18)1 需求分析该计算器程序除了具备加减乘除基本功能外,还有清零键C、CE和退格键Backspace,和一些部分的科学计算方法,包括开方、求倒、百分比,由于时间问题,之后会完善键盘事件的监听功能。

JAVA实现简单计算器

JAVA实现简单计算器

JAVA实现简单计算器```import java.util.Scanner;public class Calculatorpublic static void main(String[] args)Scanner input = new Scanner(System.in);System.out.println("欢迎使用简单计算器!");boolean running = true;while (running)System.out.println("请输入计算表达式(格式:操作数运算符操作数,例如:2 + 3),输入 exit 退出:");String expression = input.nextLine(;if (expression.equalsIgnoreCase("exit"))running = false;continue;}String[] tokens = expression.split(" ");if (tokens.length != 3)System.out.println("输入不合法,请重新输入!");continue;}trydouble operand1 = Double.parseDouble(tokens[0]);String operator = tokens[1];double operand2 = Double.parseDouble(tokens[2]);double result = calculate(operand1, operand2, operator);System.out.println("计算结果为:" + result);} catch (NumberFormatException e)System.out.println("操作数必须为数字,请重新输入!");} catch (IllegalArgumentException e)System.out.println(e.getMessage();}}System.out.println("感谢使用简单计算器,再见!");}public static double calculate(double operand1, double operand2, String operator)double result;switch (operator)case "+":result = operand1 + operand2;break;case "-":result = operand1 - operand2;break;case "*":result = operand1 * operand2;break;case "/":if (operand2 == 0)throw new IllegalArgumentException("除数不能为零!"); }result = operand1 / operand2;break;default:throw new IllegalArgumentException("运算符不合法!"); }return result;}```以上是一个简单的JAVA实现计算器的程序。

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

简易计算器总结1、计算器设计背景日常生活中我们经常会遇到一些小型数据计算的问题,本课程就是以此为出发点,设计了这样一个简单的计算器,用以实现基本的数学运算。

在java语言当中通过定义类,类中的各种方法实现对计算器相关功能的实现,并通过与用户自己手动输入并选择运算功能实现计算功能,是一个完全由用户控制的简易计算器。

2、需求环境硬件要求:一台计算机。

软件配置:WINDOWS系统、JDK 1.7、myeclipse3、计算器设计思路计算器最主要的就是实用性,要简单,便于操作。

程序界面是一个窗口的形式展现并由用户自己完全手动控制。

并以设计的要求为基础,在实现课程设计所给的功能以外,要对界面的美观进行了优化,看起来更人性化。

4、计算器实现代码package com.cqeec.sc;import java.awt.BorderLayout;import java.awt.Color;import java.awt.Dimension;import java.awt.Font;import java.awt.GridLayout;import java.awt.Insets;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.KeyEvent;import javax.swing.BorderFactory;import javax.swing.ImageIcon;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JMenu;import javax.swing.JMenuBar;import javax.swing.JOptionPane;import javax.swing.JPanel;import javax.swing.JTextField;import javax.swing.border.BevelBorder;public class Calculator extends JFrame {private static final long serialVersionUID = 1L;// 定义一级菜单名称private final String[] ONE_MENU_NAME = { "编辑(E)", "查看(V)", "帮助(H)" };// 定义一级菜单的热键private final int[] ONE_MENU_MNEMONIC = { KeyEvent.VK_E, KeyEvent.VK_V, KeyEvent.VK_H };// 定义菜单private JMenu[] oneMenu;// 定义显示器private JTextField display;// 定义左边面板MC、MR、MS、M+操作按钮标签private static final String[] BUTTON_MX_NAME = { "MC", "MR", "MS", "M+" };// 定义左边面板MC、MR、MS、M+操作按钮private JButton[] buttonMX;// 定义清除系列按钮标签private static final String[] BUTTON_CLEAR_NAME = { "Backspace", "CE", "C" };// 定义清除系统按钮private JButton[] buttonClear;// 定义数字,运算符,功能等按钮private static final String[] BUTTON_AN_NAME = { "1/x", "log", "7", "8", "9", "÷", "n!", "sqrt", "4", "5", "6", "×", "sin", "x^2", "1", "2","3", "-", "cos", "x^3", "0", "±", ".", "+", "tan", "%", "π", "e","\' \"", "=" };private JButton[] buttonAN;// M的值private double m;// 计算器标签,同时也用于显示M变量的值private JLabel labelCalculator;// 结果private double result;// 标志量,true表示开始新的输入,false表示不是private boolean isStratNewInput;// 保存运算符private String operator = "=";public Calculator() {this.setFrame();// 创建菜单this.createMenu();}private void setFrame() {// 设置窗体标题this.setTitle("计算器");// 改变大小this.setSize(500, 400);// 使窗体居于屏幕中间this.setLocationRelativeTo(null);// 设置窗体的默认关闭操作this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);// 让窗体不能改变大小this.setResizable(false);// 更改窗体的图标this.setIconImage(new ImageIcon("images/jisuanqi.jpg").getImage());}private void createMenu() {JMenuBar menuBar = new JMenuBar();// 创建菜单oneMenu = new JMenu[ONE_MENU_NAME.length];// 通过循环将一级菜单创建出来并添加到菜单栏for (int i = 0; i < ONE_MENU_NAME.length; i++) {// 创建一级菜单并保存到数组oneMenu[i] = new JMenu(ONE_MENU_NAME[i]);// 设置一级菜单栏热键oneMenu[i].setMnemonic(ONE_MENU_MNEMONIC[i]);// 将一级菜单添加到菜单栏menuBar.add(oneMenu[i]);}// 将菜单栏添加到窗体this.setJMenuBar(menuBar);// 获取窗体的内容面板的布局管理器BorderLayout layout = (BorderLayout) this.getContentPane().getLayout();// 设置垂直间距layout.setVgap(5);// 创建显示器display = new JTextField("0");display.setHorizontalAlignment(JTextField.RIGHT);// 设置字体大小display.setFont(new Font("", Font.ITALIC, 38));// 设置禁用显示器display.setEnabled(false);// 设置显示器与文本距离display.setMargin(new Insets(5, 0, 5, 5));// 设置显示器位置this.add(display, BorderLayout.NORTH);// 创建左边面板JPanel leftPanel = new JPanel(new GridLayout(5, 1, 0, 5)); // 设置面板的宽度leftPanel.setPreferredSize(new Dimension(80, 80));// 创建计算器标签labelCalculator = new JLabel("计算器");// 设置标签文字居中对齐labelCalculator.setHorizontalAlignment(JLabel.CENTER);// 设置计算器标签凹下去的效果labelCalculator.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED));// 将计算器面板添加到左面板上leftPanel.add(labelCalculator);MAction mAction = new MAction();// 创建M系列按钮// 分配M系列按钮数组大小buttonMX = new JButton[BUTTON_MX_NAME.length];// 循环创建M系列按钮for (int n = 0; n < BUTTON_MX_NAME.length; n++) { // 创建按钮并存入数组中buttonMX[n] = new JButton(BUTTON_MX_NAME[n]);// 设置按钮不要焦点框buttonMX[n].setFocusable(false);// 设置按钮前景色buttonMX[n].setForeground(Color.red);// 设置按钮动作命令buttonMX[n].setActionCommand(BUTTON_MX_NAME[n]);buttonMX[n].addActionListener(mAction);// 添加按钮动作监听buttonMX[n].addActionListener(mAction);if (n == 0 || n == 1) {buttonMX[n].setEnabled(false);}// 将按钮添加到左面板上leftPanel.add(buttonMX[n]);}// 将左面板添加到窗体的左边this.add(leftPanel, BorderLayout.WEST);// 定义右面板JPanel rightPanel = new JPanel(new BorderLayout(0, 5));// 定义Backspace、CE、C按钮Clear clearProcess = new Clear();JPanel topPanel = new JPanel(new GridLayout(1, 3, 6, 0)); topPanel.setPreferredSize(new Dimension(0, 40));buttonClear = new JButton[BUTTON_CLEAR_NAME.length];for (int i = 0; i < BUTTON_CLEAR_NAME.length; i++) { buttonClear[i] = new JButton(BUTTON_CLEAR_NAME[i]);buttonClear[i].setFocusable(false);buttonClear[i].setForeground(Color.BLACK);buttonClear[i].setActionCommand(BUTTON_CLEAR_NAME[i]);buttonClear[i].addActionListener(clearProcess);topPanel.add(buttonClear[i]);}// 将Backspace、CE、C按钮面板放到右面板北边rightPanel.add(topPanel, BorderLayout.NORTH);// 定义数字按钮事件处理程序类对象NumAction numAction = new NumAction();SignAction signAction = new SignAction();// 定义数字、运算符、功能等按钮JPanel bottomPanel = new JPanel(new GridLayout(5, 6, 8, 8)); buttonAN = new JButton[BUTTON_AN_NAME.length];for (int i = 0; i < BUTTON_AN_NAME.length; i++) { buttonAN[i] = new JButton(BUTTON_AN_NAME[i]);buttonAN[i].setFocusable(false);// 设置按钮动作命令buttonAN[i].setActionCommand(BUTTON_AN_NAME[i]);// 为数字按钮添加监听if ("0123456789±".contains(BUTTON_AN_NAME[i])) {buttonAN[i].addActionListener(numAction);}if (".".equals(BUTTON_AN_NAME[i])) {buttonAN[i].addActionListener(new DotAction());}// 定义按钮文字颜色if ("÷×-+=".indexOf(BUTTON_AN_NAME[i]) >= 0) {buttonAN[i].setForeground(Color.RED);buttonAN[i].addActionListener(signAction);} else if ("πe\' \"".indexOf(BUTTON_AN_NAME[i]) >= 0) {buttonAN[i].setForeground(Color.YELLOW);buttonAN[i].addActionListener(signAction);} else if ("0123456789±.".indexOf(BUTTON_AN_NAME[i]) >= 0) { buttonAN[i].setForeground(Color.BLUE);buttonAN[i].setActionCommand(BUTTON_AN_NAME[i]);buttonAN[i].addActionListener(signAction);} else {buttonAN[i].setForeground(Color.MAGENTA);buttonAN[i].setActionCommand(BUTTON_AN_NAME[i]);buttonAN[i].addActionListener(signAction);}bottomPanel.add(buttonAN[i]);// 将数字、运算符、功能等按钮面板放到右面板的中间rightPanel.add(bottomPanel, BorderLayout.CENTER);// 将右面板添加到窗体this.add(rightPanel, BorderLayout.CENTER);// 显示窗体this.setVisible(true);}}/** 数字、±(正负号)按钮事件处理程序类*/class NumAction implements ActionListener {public void actionPerformed(ActionEvent e) {// 获取事件源对象传过来的动作命令String cmd = e.getActionCommand();if (isStratNewInput) {display.setText("");isStratNewInput = false;}if ("±".equals(cmd)) {// 正负号if ("0".equals(display.getText())) {display.setText("-");} else {double num;String strNum = display.getText();if (strNum.contains(".")) {num = Double.parseDouble(strNum) * -1;strNum = String.valueOf(num);} else {num = Double.parseDouble(strNum) * -1;strNum = String.valueOf(num);if (strNum.contains("E")) {} else {strNum = strNum.substring(0, strNum.length() - 2);}}display.setText(strNum);}} else {// 数字if ("0".equals(display.getText())) {display.setText("");}display.setText(display.getText() + cmd);}}}/*** 小数点按钮事件处理程序*/class DotAction implements ActionListener {public void actionPerformed(ActionEvent e) {if (!display.getText().contains(".")) {display.setText(display.getText() + ".");}}}/*** Backspace、CE、C按钮事件处理程序类*/class Clear implements ActionListener {public void actionPerformed(ActionEvent e) {String cmd = e.getActionCommand();if ("Backspace".equals(cmd)) {// 删除一个String strNum = display.getText();if (strNum.length() == 0 || "0".equals(strNum)) {strNum = "0";} else {strNum = strNum.substring(0, strNum.length() - 1);strNum = "".equals(strNum) ? "0" : strNum;}display.setText(strNum);} else if ("CE".equals(cmd)) {// 清除显示器上的数字,显示零display.setText("0");} else if ("C".equals(cmd)) {// 清除M存储的值和显示器上的数字,显示零display.setText("0");labelCalculator.setText("计算器");m = 0;result = 0;isStratNewInput = false;}}}/*** MC、MR、MS、M+按钮事件处理程序类*/class MAction implements ActionListener {public void actionPerformed(ActionEvent e) {String cmd = e.getActionCommand();if ("MC".equals(cmd)) {labelCalculator.setText("计算器");m = 0;buttonMX[0].setEnabled(false);buttonMX[1].setEnabled(false);} else if ("MR".equals(cmd)) {String strM = String.valueOf(m);if (strM.charAt(strM.length() - 1) == '0') {strM = strM.substring(0, strM.length() - 2);}display.setText(strM);} else if ("MS".equals(cmd)) {String strNum = display.getText();m = Double.parseDouble(strNum);strNum = String.valueOf(m);if (strNum.charAt(strNum.length() - 1) == '0') {strNum = strNum.substring(0, strNum.length() - 2);}labelCalculator.setText(String.valueOf(m));buttonMX[0].setEnabled(true);buttonMX[1].setEnabled(true);} else if ("M+".equals(cmd)) {m = m + m;labelCalculator.setText(String.valueOf(m));buttonMX[0].setEnabled(true);buttonMX[1].setEnabled(true);}}}class SignAction implements ActionListener {public void actionPerformed(ActionEvent e) {String cmd = e.getActionCommand();double num = Double.parseDouble(display.getText());if ("1/x".equals(cmd)) {if (num == 0) {// 弹出提示JOptionPane.showMessageDialog(null,"<html>分母<span style=\"color:red;\">不能</span>为零!</html>","错误", JOptionPane.ERROR_MESSAGE);} else {display.setText(String.valueOf(1 / num));}} else if ("log".equals(cmd)) {if (num <= 0) {// 弹出提示JOptionPane.showMessageDialog(null, "输入的指数必须大于零", "错误",JOptionPane.ERROR_MESSAGE);} else {display.setText(String.valueOf(Math.log(num)));}} else if ("n!".equals(cmd)) {if (num < 0) {JOptionPane.showMessageDialog(null, "计算阶乘的数不能小于零", "错误",JOptionPane.ERROR_MESSAGE);} else {double s = 1;for (int i = 1; i < num; i++) {s *= i;}display.setText(String.valueOf(s));}} else if ("sqrt".equals(cmd)) {if (num <= 0) {// 弹出提示JOptionPane.showMessageDialog(null, "输入的数必须大于零", "错误",JOptionPane.ERROR_MESSAGE);} else {display.setText(String.valueOf(Math.sqrt(num)));}} else if ("sin".equals(cmd)) {display.setText(String.valueOf(Math.sin(num)));} else if ("x^2".equals(cmd)) {display.setText(String.valueOf(Math.pow(num, 2)));} else if ("cos".equals(cmd)) {display.setText(String.valueOf(Math.cos(num)));} else if ("x^3".equals(cmd)) {display.setText(String.valueOf(Math.pow(num, 3)));} else if ("tan".equals(cmd)) {display.setText(String.valueOf(Math.tan(num)));} else if ("%".equals(cmd)) {num = num / 100;display.setText(String.valueOf(num));} else if ("π".equals(cmd)) {display.setText(String.valueOf(Math.PI));} else if ("e".equals(cmd)) {String strNum = display.getText();if (strNum.contains(".")) {String strZS;// 小数strNum = String.valueOf(Double.parseDouble(strNum));if (strNum.contains("E")) {display.setText(strNum.replace('E', 'e'));} else {// 取整数部分strZS = strNum.substring(0, strNum.indexOf("."));// 判断小数的整数部分长度是否大于1strZS = String.valueOf(Math.abs(Long.parseLong(strZS)));if (strZS.length() > 1) {// 左移小数点strZS = strZS.substring(0, 1)+ "."+ strZS.substring(1, strZS.length())+ strNum.substring(strNum.indexOf(".") + 1,strNum.length()) + "e+"+ (strZS.length() - 1);if (strNum.contains("-")) {strZS = "-" + strZS;}display.setText(strZS);} else {if ("0".equals(strZS) || "-0".equals(strZS)) {// 取出小数部分String strXS = strNum.substring(strNum.indexOf(".") + 1,strNum.length());// 统计小数点后零的个数+1(次方数)int count = 0;for (int i = 0; strXS.charAt(i) == '0'; i++) {count++;}count = count + 1;// 取出底数strXS = String.valueOf(Long.parseLong(strXS));strXS = strXS.substring(0, 1) + "."+ strXS.substring(1, strXS.length());// 连接strNum = strXS + "e-" + count;} else {// 不动strNum = strNum + "e+0";}display.setText(strNum);}}} else {// 不是小数double ds;if (strNum.contains("-")) {ds = Double.parseDouble(strNum.substring(0, 2) + "."+ strNum.substring(2, strNum.length()));} else {ds = Double.parseDouble(strNum.substring(0, 1) + "."+ strNum.substring(1, strNum.length()));}strNum = String.valueOf(ds) + "e+" + (strNum.length() - 1);display.setText(strNum);}} else if ("\' \"".equals(cmd)) {} else if ("÷".equals(cmd)) {calculate(cmd);} else if ("×".equals(cmd)) {calculate(cmd);} else if ("+".equals(cmd)) {calculate(cmd);} else if ("-".equals(cmd)) {calculate(cmd);} else if ("=".equals(cmd)) {calculate(cmd);}}public void calculate(String opr) {// 取当前显示器上的数double n = Double.parseDouble(display.getText());// 根据上一次的运算符进行计算if ("÷".equals(operator)) {result /= n;// result=result/n;} else if ("×".equals(operator)) {result *= n;} else if ("+".equals(operator)) {result += n;} else if ("-".equals(operator)) {result -= n;} else if ("=".equals(operator)) {result = n;}// 将计算的结果显示到显示器上display.setText(String.valueOf(result));// 将新输入的运算符存入到原operator = opr;// 开启一个新数的输入isStratNewInput = true;}}}5、计算器实现实例6、计算器设计总结虽然在这次的课程设计中有很多的不足,但是我也收获了很多。

相关文档
最新文档