用java.EE编写计算器程序代码

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了用java.EE编写计算器程序代码相关的知识,希望对你有一定的参考价值。

java EE是java企业级开发平台的意思,实在是看不出跟计算器这种小程序有什么关联。不知道楼主要找的是不是这个。
package ex1;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DecimalFormat;

import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.JTextField;

public class Calcutor extends JFrame
private JTextField tf;
private JPanel panel1, panel2, panel3, panel4;
private JMenuBar myBar;
private JMenu menu1, menu2, menu3;
private JMenuItem editItem1, editItem2, help1, help2, help3;
private JRadioButtonMenuItem seeItem1, seeItem2;//单选框
private JCheckBoxMenuItem seeItem3;//复选框
private ButtonGroup bgb;
private String back;
private boolean IfResult = true, flag = false;
private String oper = "=";
private double result = 0;
private Num numActionListener;
private DecimalFormat df;

public Calcutor()
super("科学计算器");//设置标题栏

df = new DecimalFormat("#.####");//保留四位小数

this.setLayout(new BorderLayout(10, 5));
panel1 = new JPanel(new GridLayout(1, 3, 10, 10));
panel2 = new JPanel(new GridLayout(5, 6, 5, 5));//5行6列
panel3 = new JPanel(new GridLayout(5, 1, 5, 5));
panel4 = new JPanel(new BorderLayout(5, 5));

/**
* 菜单栏
*/
myBar = new JMenuBar();
menu1 = new JMenu("编辑(E)");
menu2 = new JMenu("查看(V)");
menu3 = new JMenu("帮助(H)");

menu1.setFont(new Font("宋体", Font.PLAIN, 12));
menu2.setFont(new Font("宋体", Font.PLAIN, 12));
menu3.setFont(new Font("宋体", Font.PLAIN, 12));

/**
* 编辑栏
*/
editItem1 = new JMenuItem("复制(C) Ctrl+C");
editItem2 = new JMenuItem("粘贴(P) Ctrl+V");

editItem1.setFont(new Font("宋体",Font.PLAIN,12));
editItem2.setFont(new Font("宋体",Font.PLAIN,12));

/**
* 查看栏
*/
seeItem1 = new JRadioButtonMenuItem("科学型(T)");
seeItem2 = new JRadioButtonMenuItem("标准型(S)");
seeItem3 = new JCheckBoxMenuItem("数字分组(I)");

seeItem1.setFont(new Font("宋体",Font.PLAIN,12));
seeItem2.setFont(new Font("宋体",Font.PLAIN,12));
seeItem3.setFont(new Font("宋体",Font.PLAIN,12));

/**
* 帮助栏
*/
help1 = new JMenuItem("帮助主题(H)");
help2 = new JMenuItem("关于计算器(A)");

help1.setFont(new Font("宋体",Font.PLAIN,12));
help2.setFont(new Font("宋体",Font.PLAIN,12));

bgb = new ButtonGroup();//选项组

menu1.add(editItem1);
menu1.add(editItem2);

menu2.add(seeItem1);
menu2.add(seeItem2);
menu2.addSeparator();//添加一条分割线
menu2.add(seeItem3);

menu3.add(help1);
menu3.addSeparator();//添加一条分割线
menu3.add(help2);

myBar.add(menu1);
myBar.add(menu2);
myBar.add(menu3);

this.setJMenuBar(myBar);

numActionListener = new Num();//实现数字监听

/**
* 文本域,即为计算器的屏幕显示区域
*/
tf = new JTextField();
tf.setEditable(false);//文本区域不可编辑
tf.setBackground(Color.white);//文本区域的背景色
tf.setHorizontalAlignment(JTextField.RIGHT);//文字右对齐
tf.setText("0");
tf.setBorder(BorderFactory.createLoweredBevelBorder());
init();//对计算器进行初始化


/**
* 初始化操作
* 添加按钮
*/
private void init()
addButton(panel1, "Backspace", new Clear(), Color.red);
addButton(panel1, "CE", new Clear(), Color.red);
addButton(panel1, "C", new Clear(), Color.red);

addButton(panel2, "1/x", new Signs(), Color.magenta);
addButton(panel2, "log", new Signs(), Color.magenta);
addButton(panel2, "7", numActionListener, Color.blue);
addButton(panel2, "8", numActionListener, Color.blue);
addButton(panel2, "9", numActionListener, Color.blue);
addButton(panel2, "÷", new Signs(), Color.red);

addButton(panel2, "n!", new Signs(), Color.magenta);
addButton(panel2, "sqrt", new Signs(), Color.magenta);
addButton(panel2, "4", numActionListener, Color.blue);
addButton(panel2, "5", numActionListener, Color.blue);
addButton(panel2, "6", numActionListener, Color.blue);
addButton(panel2, "×", new Signs(), Color.red);

addButton(panel2, "sin", new Signs(), Color.magenta);
addButton(panel2, "x^2", new Signs(), Color.magenta);
addButton(panel2, "1", numActionListener, Color.blue);
addButton(panel2, "2", numActionListener, Color.blue);
addButton(panel2, "3", numActionListener, Color.blue);
addButton(panel2, "-", new Signs(), Color.red);

addButton(panel2, "cos", new Signs(), Color.magenta);
addButton(panel2, "x^3", new Signs(), Color.magenta);
addButton(panel2, "0", numActionListener, Color.blue);
addButton(panel2, "-/+", new Clear(), Color.blue);
addButton(panel2, ".", new Dot(), Color.blue);
addButton(panel2, "+", new Signs(), Color.red);

addButton(panel2, "tan", new Signs(), Color.magenta);
addButton(panel2, "%", new Signs(), Color.magenta);
addButton(panel2, "π", numActionListener, Color.orange);
addButton(panel2, "e", numActionListener, Color.orange);
addButton(panel2, "′″", new Signs(), Color.orange);
addButton(panel2, "=", new Signs(), Color.red);

JButton btns = new JButton("计算器");
btns.setBorder(BorderFactory.createLoweredBevelBorder());
btns.setEnabled(false);//按钮不可操作
btns.setPreferredSize(new Dimension(20, 20));

panel3.add(btns);//加入按钮
addButton(panel3, "MC", null, Color.red);
addButton(panel3, "MR", null, Color.red);
addButton(panel3, "MS", null, Color.red);
addButton(panel3, "M+", null, Color.red);

panel4.add(panel1, BorderLayout.NORTH);
panel4.add(panel2, BorderLayout.CENTER);
this.add(tf, BorderLayout.NORTH);
this.add(panel3, BorderLayout.WEST);
this.add(panel4);

pack();
this.setResizable(false);//窗口不可改变大小
this.setLocation(300, 200);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

/**
* 统一设置按钮的的使用方式
* @param panel
* @param name
* @param action
* @param color
*/
private void addButton(JPanel panel, String name, ActionListener action, Color color)
JButton bt = new JButton(name);
panel.add(bt);//在面板上增加按钮
bt.setForeground(color);//设置前景(字体)颜色
bt.addActionListener(action);//增加监听事件

/**
* 计算器的基础操作(+ - × ÷)
* @param x
*/
private void getResult (double x)
if(oper == "+")result += x;
else if(oper == "-")result -= x;
else if(oper == "×")result *= x;
else if(oper == "÷")result /= x;
else if(oper == "=")result = x;
tf.setText(df.format(result));

/**
* 运算符号的事件监听
*/
class Signs implements ActionListener
public void actionPerformed(ActionEvent e)
/*
* 用ActionEvent对象的getActionCommand()方法
* 取得与引发事件对象相关的字符串
*/
String str = e.getActionCommand();

/* sqrt求平方根 */
if(str.equals("sqrt"))
double i = Double.parseDouble(tf.getText());
if(i>=0)
/*
* String.valueOf() 转换为字符串
* df.format() 按要求保留四位小数
* Math.sqrt() 求算数平方根
*/
tf.setText(String.valueOf(df.format(Math.sqrt(i))));

else
tf.setText("负数不能开平方根");



/* log求常用对数 */
else if(str.equals("log"))
double i = Double.parseDouble(tf.getText());
if(i>0)
tf.setText(String.valueOf(df.format(Math.log(i))));
else
tf.setText("负数不能求对数");



/* %求百分比 */
else if(str.equals("%"))
tf.setText(df.format(Double.parseDouble(tf.getText()) / 100));


/* 1/x求倒数 */
else if(str.equals("1/x"))
if(Double.parseDouble(tf.getText()) == 0)
tf.setText("除数不能为零");
else
tf.setText(df.format(1 / Double.parseDouble(tf.getText())));



/* sin求正弦函数 */
else if(str.equals("sin"))
double i = Double.parseDouble(tf.getText());
tf.setText(String.valueOf(df.format(Math.sin(i))));


/* cos求余弦函数 */
else if(str.equals("cos"))
double i = Double.parseDouble(tf.getText());
tf.setText(String.valueOf(df.format(Math.cos(i))));


/* tan求正切函数 */
else if(str.equals("tan"))
double i = Double.parseDouble(tf.getText());
tf.setText(String.valueOf(df.format(Math.tan(i))));


/* n!求阶乘 */
else if(str.equals("n!"))
double i = Double.parseDouble(tf.getText());
if((i%2==0)||(i%2==1))//判断为整数放进行阶乘操作

int j = (int)i;//强制类型转换
int result=1;
for(int k=1;k<=j;k++)
result *= k;
tf.setText(String.valueOf(result));

else

tf.setText("无法进行阶乘");



/* x^2求平方 */
else if(str.equals("x^2"))
double i = Double.parseDouble(tf.getText());
tf.setText(String.valueOf(df.format(i*i)));


/* x^3求立方 */
else if(str.equals("x^3"))
double i = Double.parseDouble(tf.getText());
tf.setText(String.valueOf(df.format(i*i*i)));


/* ′″角度转换 */
/**
* 将角度值转换成弧度值,方便三角函数的计算
*/
else if(str.equals("′″"))
double i = Double.parseDouble(tf.getText());
tf.setText(String.valueOf(i/180*Math.PI));


else
if(flag)
IfResult = false;

if(IfResult)
oper = str;
else
getResult(Double.parseDouble(tf.getText()));
oper = str;
IfResult = true;




/**
* 清除按钮的事件监听
*/
class Clear implements ActionListener
public void actionPerformed(ActionEvent e)
/*
* 用ActionEvent对象的getActionCommand()方法
* 取得与引发事件对象相关的字符串
*/
String str = e.getActionCommand();
if(str == "C")
tf.setText("0");
IfResult = true;
result = 0;
else if(str == "-/+")
double i = 0 - Double.parseDouble(tf.getText().trim());
tf.setText(df.format(i));
else if(str == "Backspace")
if(Double.parseDouble(tf.getText()) > 0)
if(tf.getText().length() > 1)
tf.setText(tf.getText().substring(0, tf.getText().length() - 1));
//使用退格删除最后一位字符
else
tf.setText("0");
IfResult = true;

else
if(tf.getText().length() > 2)
tf.setText(tf.getText().substring(0, tf.getText().length() - 1));
else
tf.setText("0");
IfResult = true;


else if(str == "CE")
tf.setText("0");
IfResult = true;



/**
* 数字输入的事件监听
*/
class Num implements ActionListener
public void actionPerformed(ActionEvent e)
String str = e.getActionCommand();
if(IfResult)
tf.setText("");
IfResult = false;

if(str=="π")

tf.setText(String.valueOf(Math.PI));

else if(str=="e")

tf.setText(String.valueOf(Math.E));

else
tf.setText(tf.getText().trim() + str);
if(tf.getText().equals("0"))
tf.setText("0");
IfResult = true;
flag = true;




/**
* 小数点的事件监听
*/
class Dot implements ActionListener
public void actionPerformed(ActionEvent e)
IfResult = false;
if(tf.getText().trim().indexOf(".") == -1)
tf.setText(tf.getText() + ".");



/**
* main方法
*/
public static void main(String[] args)
new Calcutor().setVisible(true);

参考技术A import java.awt.BorderLayout;
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;

public class 计算机 extends JFrame
//第一个数
String firstNum="";
//第二个数
String secondNum="";
//判断是否点击了= - * /
boolean flag=true;
//操作标记
String biaoji="";

public 计算机()

setDefaultCloseOperation(DISPOSE_ON_CLOSE);

final JTextField tf_num=new JTextField();
add(tf_num,BorderLayout.NORTH);

JPanel p=new JPanel();
p.setLayout(new GridLayout(4,4));
String str="789/456*123-0.=+";
for(int i=0;i<str.length();i++)
char c=str.charAt(i);
JButton b=new JButton(c+"");
p.add(b);
b.addActionListener(new ActionListener()

public void actionPerformed(ActionEvent arg0)
////得到选中的按钮
Object obj=arg0.getSource();
////强制转换成button
JButton select_btn=(JButton) obj;
////得到按钮上的信息
String values=select_btn.getText();
//////////////////判断是否为数字
if("1234567890.".indexOf(values)>=0)

if(flag)

String oid=tf_num.getText();
tf_num.setText(oid+values);

else

tf_num.setText(values);
flag=true;



/////////////////判断按钮为+ - * /中一个
if("+-*/".indexOf(values)>=0)

firstNum=tf_num.getText();
biaoji=values;
flag=false;


if(values.equals("="))

double sum=0;
secondNum=tf_num.getText();

if(biaoji.equals("+"))

sum=Double.parseDouble(firstNum)+Double.parseDouble(secondNum);



if(biaoji.equals("-"))

sum=Double.parseDouble(firstNum)-Double.parseDouble(secondNum);



if(biaoji.equals("*"))

sum=Double.parseDouble(firstNum)*Double.parseDouble(secondNum);



if(biaoji.equals("/"))

sum=Double.parseDouble(firstNum)/Double.parseDouble(secondNum);



tf_num.setText(sum+"");
flag=false;





);



add(p);
setSize(200, 200);
setVisible(true);



public static void main(String[] args)

new 计算机();


用java编写一个简单计算器

编写一个GUI程序,利用第一和第二个文本框分别输入两个整数,在单击运算符按钮时,则在第一和第二个文本框之间显示运算符;单击‘=’按钮,则在第三个文本框中显示第一和第二个文本框的运算结果。
就按照我给的题目,写出图片一样的程序

参考技术A

/*

 * @(#)JCalculator.java 1.00 06/17/2015

 */

 

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

 

/**

 * A simple calculator program.

 * <p>I saw this program in a QQ group, and help a friend correct it.</p>

 *

 * @author Singyuen Yip

 * @version 1.00 12/29/2009

 * @see JFrame

 * @see ActionListener

 */

public class JCalculator extends JFrame implements ActionListener

    /**

     * Serial Version UID

     */

    private static final long serialVersionUID = -169068472193786457L;

    /**

     * This class help close the Window.

     * @author Singyuen Yip

     *

     */

    private class WindowCloser extends WindowAdapter

       public void windowClosing(WindowEvent we)

           System.exit(0);

       

    

 

    int i;

    // Strings for Digit & Operator buttons.

    private final String[] str =  "7", "8", "9", "/", "4", "5", "6", "*","1",

           "2", "3", "-", ".", "0", "=", "+" ;

    // Build buttons.

    JButton[] buttons = new JButton[str.length];

    // For cancel or reset.

    JButton reset = new JButton("CE");

    // Build the text field to show the result.

    JTextField display = new JTextField("0");

   

    /**

     * Constructor without parameters.

     */

    public JCalculator()

       super("Calculator");

       // Add a panel.

       JPanel panel1 = new JPanel(new GridLayout(4, 4));

       // panel1.setLayout(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.setLayout(new BorderLayout());

       panel2.add("Center", display);

       panel2.add("East", reset);

       // JPanel panel3 = new Panel();

       getContentPane().setLayout(new BorderLayout());

       getContentPane().add("North", panel2);

       getContentPane().add("Center", panel1);

       // Add action listener for each digit & operator button.

       for (i = 0; i < str.length; i++)

           buttons[i].addActionListener(this);

       // Add listener for "reset" button.

       reset.addActionListener(this);

       // Add listener for "display" button.

       display.addActionListener(this);

       // The "close" button "X".

       addWindowListener(new WindowCloser());

       // Initialize the window size.

       setSize(800, 800);

       // Show the window.

       // show(); Using show() while JDK version is below 1.5.

       setVisible(true);

       // Fit the certain size.

       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);

       else

           handleOperator(label);

    

    // Is the first digit pressed?

    boolean isFirstDigit = true;

    /**

     * Number handling.

     * @param key the key of the button.

     */

    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;

    

   

    /**

     * Reset the calculator.

     */

    public void handleReset()

       display.setText("0");

       isFirstDigit = true;

       operator = "=";

    

 

    double number = 0.0;

    String operator = "=";

   

    /**

     * Handling the operation.

     * @param key pressed operator's key.

     */

    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();

    


运行界面:

参考技术B package swing;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
@SuppressWarnings("serial")
public class Calculator extends JFrame
JTextField jt1 ,jt2 ,jt3;
JLabel jLabel;
JButton equButton,addButton,reduceButton,mulButton,divButton;
public Calculator() 
super("简易计算器");
JPanel contentPanel = new JPanel();
contentPanel.setLayout(new GridLayout(2, 0));
JPanel uJPanel = new JPanel();
Dimension preferredSize = new Dimension(50, 29);
GridBagConstraints gbc = new GridBagConstraints();
uJPanel.setLayout(new GridBagLayout());
gbc.gridx = GridBagConstraints.RELATIVE;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(1, 2, 1, 2);
jt1 = new JTextField(4);
jLabel = new JLabel();
jLabel.setPreferredSize(new Dimension(10, 29));
jt2 = new JTextField(4);
equButton = new JButton("=");
ActionListener myActionListener = new MyActionListener();
equButton.addActionListener(myActionListener);
jt3 = new JTextField(8);
jt1.setPreferredSize(preferredSize);
jt2.setPreferredSize(preferredSize);
jt3.setPreferredSize(preferredSize);
uJPanel.add(jt1,gbc);
uJPanel.add(jLabel,gbc);
uJPanel.add(jt2,gbc);
uJPanel.add(equButton,gbc);
gbc.weightx = 1;
uJPanel.add(jt3,gbc);
contentPanel.add(uJPanel);
JPanel dJPanel = new JPanel();
dJPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 8, 2));
addButton = new JButton("+");
reduceButton = new JButton("-");
mulButton = new JButton("*");
divButton = new JButton("/");
addButton.addActionListener(myActionListener);
reduceButton.addActionListener(myActionListener);
mulButton.addActionListener(myActionListener);
divButton.addActionListener(myActionListener);
dJPanel.add(addButton);
dJPanel.add(reduceButton);
dJPanel.add(mulButton);
dJPanel.add(divButton);
contentPanel.add(dJPanel);
this.setContentPane(contentPanel);
this.pack();
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(3);
this.setVisible(true);

class MyActionListener implements ActionListener
Double d1,d2,d3;
String operator = "";
public void actionPerformed(ActionEvent e) 
String fun = e.getActionCommand();
if (!fun.equals("=")) 
jLabel.setText(fun);
operator = fun;
else 
d1 = jt1.getText().equals("")?null:Double.valueOf(jt1.getText());
d2 = jt2.getText().equals("")?null:Double.valueOf(jt2.getText());
d3 = calculate(d1,d2,operator);
jt3.setText(d3==null ? "":d3.toString());
jt3.setCaretPosition(0);



Double calculate(Double d1,Double d2,String operator)
if (d1 == null || d2 == null) 
return null;

Double d3 = null;
switch (operator) 
case "+":
d3 = d1 + d2;
break;
case "-":
d3 = d1 - d2;
break;
case "*":
d3 = d1 * d2;
break;
case "/":
d3 = d1 / d2;
break;

return d3;

public static void main(String[] args) 
new Calculator();

本回答被提问者和网友采纳
参考技术C 我已经写好了。需要的话,撩我追问

咋给我

追答

看我的名字。

追问

直接在这里回答不可以吗?

参考技术D 不错,都有现成的了
~~
第5个回答  2018-01-17 你这是样本吗?不是已经写好了?追问

哪有?那些都是很复杂的,我并不需要那么复杂的

追答

你什么要求

追问

就按照我给的那个要求做就可以了

以上是关于用java.EE编写计算器程序代码的主要内容,如果未能解决你的问题,请参考以下文章

Java EE开发技术课程第五周(Applet程序组件与AJAX技术)

JAVA EE 基本了解

使用Java EE基本技术开发简单MVC程序(含代码)

怎么用java编写echarts代码

java用啥软件编写代码

在Linux下用C语言编写程序,急求完整代码