导航:首页 > 编程语言 > java加法计算器

java加法计算器

发布时间:2022-11-08 07:30:06

A. 用java编写一个简单的计算器(包括加减乘除)图形界面

public class ItemEvent事件

{
public static void main(String args[])
{
WindowOperation win=new WindowOperation();
win.setBounds(100,100,390,360);
win.setTitle("简单计算器");
}
}

import java.awt.event.*;
import javax.swing.*;
public class OperatorListener implements ItemListener
{
JComboBox choice;
ComputerListener workTogether;
public void setJComboBox(JComboBox box)
{
choice=box;
}
public void setWorkTogether(ComputerListener computer)
{
workTogether=computer;
}
public void itemStateChanged(ItemEvent e)
{
String fuhao=choice.getSelectedItem().toString();
workTogether.setFuhao(fuhao);
}
}

B. java加法计算器代码

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener

public class NewJFrame extends javax.swing.JFrame {

public NewJFrame() {
initComponents();
}

private void initComponents() {

jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
num1 = new javax.swing.JTextField();
num2 = new javax.swing.JTextField();
result = new javax.swing.JTextField();
addBtn = new javax.swing.JButton();
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
jMenu3 = new javax.swing.JMenu();
jMenu2 = new javax.swing.JMenu();

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

jLabel1.setText("Num1:");

jLabel2.setText("Num2:");

jLabel3.setText("Num3:");

addBtn.setText("Add");
addBtn.addActionListener(new jisuanAC());

javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(53, 53, 53)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(addBtn)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
.addComponent(jLabel1)
.addGap(31, 31, 31)
.addComponent(num1, javax.swing.GroupLayout.DEFAULT_SIZE, 98, Short.MAX_VALUE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel2)
.addComponent(jLabel3))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 31, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(result)
.addComponent(num2, javax.swing.GroupLayout.DEFAULT_SIZE, 98, Short.MAX_VALUE))))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
.addGap(168, 168, 168))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(19, 19, 19)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(num1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(num2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(result, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(61, 61, 61)
.addComponent(addBtn)
.addContainerGap(81, Short.MAX_VALUE))
);

jMenu1.setText("Operation");

jMenu3.setText("Add");
jMenu1.add(jMenu3);

jMenuBar1.add(jMenu1);

jMenu2.setText("Exit");
jMenuBar1.add(jMenu2);

setJMenuBar(jMenuBar1);

javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);

pack();
}// </editor-fold>

/**
* @param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new NewJFrame().setVisible(true);
}
});
}
private class jisuanAC implements ActionListener
{

public void actionPerformed(ActionEvent e) {
if(e.getSource()== addBtn)
{
int number1 = Integer.parseInt(num1.getText());
int number2 = Integer.parseInt(num2.getText());
int rs = number1 + number2;
result.setText(String.valueOf(rs));

}
}

}

// Variables declaration - do not modify
private javax.swing.JButton addBtn;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenu jMenu2;
private javax.swing.JMenu jMenu3;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JPanel jPanel1;
private javax.swing.JTextField num1;
private javax.swing.JTextField num2;
private javax.swing.JTextField result;

}

这是只有一个加法的例子!希望帮到你

C. 求一个用JAVA编写的计算器程序(1)实现简单加、减、乘、除的运算。 (

public
MyCalculator()
{
f
=
new
JFrame("计算器ByMdou");
Container
contentPane
=
f.getContentPane();
/****************菜单的创建开始**************************************/
JMenuBar
mBar
=
new
JMenuBar();
mBar.setOpaque(true);
mEdit
=
new
JMenu("编辑(E)");
mEdit.setMnemonic(KeyEvent.VK_E);
mCopy
=
new
JMenuItem("复制(C)");
mEdit.add(mCopy);
mPaste
=
new
JMenuItem("粘贴(P)");
mEdit.add(mPaste);
mView
=
new
JMenu("查看(V)");
mView.setMnemonic(KeyEvent.VK_V);
mView.add(new
JMenuItem("标准型"));
mView.add(new
JMenuItem("科学型"));
mView.addSeparator();
mView.add(new
JMenuItem("查看分组"));
mHelp
=
new
JMenu("帮助(H)");
mHelp.setMnemonic(KeyEvent.VK_H);
mHelp.add(new
JMenuItem("帮助主题"));
mHelp.addSeparator();
mHelp.add(new
JMenuItem("关于计算器"));
mBar.add(mEdit);
mBar.add(mView);
mBar.add(mHelp);
f.setJMenuBar(mBar);
contentPane.setLayout(new
BorderLayout
());
JPanel
pTop
=
new
JPanel();
tResult
=
new
JTextField("0.",26);
tResult.setHorizontalAlignment(JTextField.RIGHT
);
tResult.setEditable(false);
pTop.add(tResult);
contentPane.add(pTop,BorderLayout.NORTH);
JPanel
pBottom
=
new
JPanel();
pBottom.setLayout(new
BorderLayout());
JPanel
pLeft
=
new
JPanel();
pLeft.setLayout(new
GridLayout(5,1,3,3));
bM
=
new
JButton("
");
bM.setEnabled(false);
pLeft.add(bM);
bOther
=
new
JButton("MC");
bOther.addActionListener(this);
bOther.setForeground(Color.RED);
bOther.setMargin(new
Insets(3,2,3,2));
pLeft.add(bOther);
bOther
=
new
JButton("MR");
bOther.addActionListener(this);
bOther.setForeground(Color.RED);
bOther.setMargin(new
Insets(3,2,3,2));
pLeft.add(bOther);
bOther
=
new
JButton("MS");
bOther.addActionListener(this);
bOther.setForeground(Color.RED);
bOther.setMargin(new
Insets(3,2,3,2));
pLeft.add(bOther);
bOther
=
new
JButton("M+");
bOther.addActionListener(this);
bOther.setForeground(Color.RED);
bOther.setMargin(new
Insets(3,2,3,2));
pLeft.add(bOther);

D. java:编写一个计算器小程序,要求可以做加减乘除运算

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Calculator extends JFrame implements ActionListener{
private static final long serialVersionUID = 8199443193151152362L;
private JButton bto_s=new JButton("sqrt"),bto_zf=new JButton("+/-"),bto_ce=new JButton("CE"),bto_c=new JButton("C"),bto_7=new JButton("7"),
bto_8=new JButton("8"),bto_9=new JButton("9"),bto_chu=new JButton("/"),bto_4=new JButton("4"),bto_5=new JButton("5"),
bto_6=new JButton("6"),bto_cheng=new JButton("*"),bto_1=new JButton("1"),bto_2=new JButton("2"),bto_3=new JButton("3"),
bto_jian=new JButton("-"),bto_0=new JButton("0"),bto_dian=new JButton("."),bto_deng=new JButton("="),bto_jia=new JButton("+");
JButton button[]={bto_s,bto_zf,bto_ce,bto_c,bto_7,bto_8,bto_9,bto_chu,bto_4,bto_5,bto_6,bto_cheng,bto_1,bto_2,bto_3,bto_jian,
bto_0,bto_dian,bto_deng,bto_jia};
private JTextField text_double;// = new JTextField("0");
private String operator = "="; //当前运算的运算符
private boolean firstDigit = true; // 标志用户按的是否是整个表达式的第一个数字,或者是运算符后的第一个数字
private double resultNum = 0.0; // 计算的中间结果
private boolean operateValidFlag = true; //判断操作是否合法
public Calculator()
{
super("Calculator");
this.setBounds(300, 300, 300, 300);
this.setResizable(false);
this.setBackground(Color.orange);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.getContentPane().setLayout(new BorderLayout());//设置布局
text_double=new JTextField("0",20);//设置文本区
text_double.setHorizontalAlignment(JTextField.RIGHT);//设置水平对齐方式未右对齐
this.getContentPane().add(text_double,BorderLayout.NORTH);//将文本区添加到Content北部
JPanel panel=new JPanel(new GridLayout(5,4));//在内容窗口添加一个网格布局
this.getContentPane().add(panel);//添加panel面板
for(int i=0;i<button.length;i++)//在面板上添加按钮
panel.add(button[i]);

for(int i=0;i<button.length;i++)
button[i].addActionListener(this);//为按钮注册
text_double.setEditable(false);//文本框不可编辑
text_double.addActionListener(this);//

this.setVisible(true);
}
public void actionPerformed(ActionEvent e)//
{
String c= e.getActionCommand();//返回与此动作相关的命令字符串。
System.out.println("##########command is "+c);
if(c.equals("C")){
handleC(); //用户按了“C”键
}
else if (c.equals("CE")) // 用户按了"CE"键
{
text_double.setText("0");
}
else if ("0123456789.".indexOf(c) >= 0) // 用户按了数字键或者小数点键
{
handleNumber(c); // handlezero(zero);
} else //用户按了运算符键
{
handleOperator(c);
}
}
private void handleC() // 初始化计算器的各种值
{
text_double.setText("0");
firstDigit = true;
operator = "=";
}
private void handleNumber(String button) {
if (firstDigit)//输入的第一个数字
{
text_double.setText(button);
} else if ((button.equals(".")) && (text_double.getText().indexOf(".") < 0))//输入的是小数点,并且之前没有小数点,则将小数点附在结果文本框的后面
//如果字符串参数作为一个子字符串在此对象中出现,则返回第一个这种子字符串的第一个字符的索引;如果它不作为一个子字符串出现,则返回 -1
{
text_double.setText(text_double.getText() + ".");
} else if (!button.equals("."))// 如果输入的不是小数点,则将数字附在结果文本框的后面
{
text_double.setText(text_double.getText() + button);
}
// 以后输入的肯定不是第一个数字了
firstDigit = false;
}
private void handleOperator(String button) {

if (operator.equals("/")) {
// 除法运算
// 如果当前结果文本框中的值等于0
if (getNumberFromText() == 0.0){
// 操作不合法
operateValidFlag = false;
text_double.setText("除数不能为零");
} else {
resultNum /= getNumberFromText();
}
} else if (operator.equals("+")){
// 加法运算
resultNum += getNumberFromText();
} else if (operator.equals("-")){
// 减法运算
resultNum -= getNumberFromText();
} else if (operator.equals("*")){
// 乘法运算
resultNum *= getNumberFromText();
} else if (operator.equals("sqrt")) {
// 平方根运算
if(getNumberFromText()<0){
operateValidFlag = false;
text_double.setText("被开方数不能为负数");}
else
resultNum = Math.sqrt(resultNum);
}
else if (operator.equals("+/-")){
// 正数负数运算
resultNum = resultNum * (-1);
} else if (operator.equals("=")){
// 赋值运算
resultNum = getNumberFromText();
}
if (operateValidFlag) {
// 双精度浮点数的运算
long t1;
double t2;
t1 = (long) resultNum;
t2 = resultNum - t1;
if (t2 == 0) {
text_double.setText(String.valueOf(t1));
} else {
text_double.setText(String.valueOf(resultNum));
}
}
operator = button; //运算符等于用户按的按钮
firstDigit = true;
operateValidFlag = true;
}
private double getNumberFromText() //从结果的文本框获取数字
{
double result = 0;
try {
result = Double.valueOf(text_double.getText()).doubleValue(); // ValueOf()返回表示指定的 double 值的 Double 实例
} catch (NumberFormatException e){
}
return result;
}
public static void main(final String[] args) {
new Calculator();
}
}

E. java编写一个计算器类

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
public class Jisuanqi extends JFrame implements ActionListener {
/**
*
*/
private static final long serialVersionUID = 1L;
Result result = new Result(); // 定义text的面板
Number_Key number_key = new Number_Key(); // 定义按钮面板
// 当点击按钮+、-、*、/时,com = true
boolean com = false;
// 当i=0时说明是我们第一次输入,字符串text不会累加
int i = 0;
// 存放text的内容
String text = "";
// 存放点击按钮+、-、*、/之前的数值
double defbutton = 0;
// +、-、*、/的代号分别为1,2,3,4
int symbol = 0;
// 构造函数
Jisuanqi() {
super("计算器"); // 设定标题
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // 设定关闭窗体时退出程序
JPanel pane = new JPanel(); // 定义主面板
pane.setLayout(new BorderLayout());
setBounds(380, 220, 30, 80); // 前两个参数是在屏幕上显示的坐标,后两个是大小
// 替换图标
ImageIcon icon = new ImageIcon("F:1.GIF");
// Jisuanqi.class.getResource("APPLE.GIF")
// );
setIconImage(icon.getImage());
pane.add(result, BorderLayout.NORTH);
pane.add(number_key, BorderLayout.CENTER);
pane.add(number_key.equal, BorderLayout.SOUTH);
number_key.one.addActionListener(this); // 对1按钮添加监听事件
number_key.two.addActionListener(this); // 对2按钮添加监听事件
number_key.three.addActionListener(this); // 对3按钮添加监听事件
number_key.four.addActionListener(this); // 对4按钮添加监听事件
number_key.five.addActionListener(this); // 对5按钮添加监听事件
number_key.six.addActionListener(this); // 对6按钮添加监听事件
number_key.seven.addActionListener(this); // 对7按钮添加监听事件
number_key.eight.addActionListener(this); // 对8按钮添加监听事件
number_key.nine.addActionListener(this); // 对9按钮添加监听事件
number_key.zero.addActionListener(this); // 对0按钮添加监听事件
number_key.ce.addActionListener(this); // 对置零按钮添加监听事件
number_key.plus.addActionListener(this); // 对+按钮添加监听事件
number_key.equal.addActionListener(this); // 对=按钮添加监听事件
number_key.sub.addActionListener(this); // 对-按钮添加监听事件
number_key.mul.addActionListener(this); // 对*按钮添加监听事件
number_key.div.addActionListener(this); // 对/按钮添加监听事件
number_key.point.addActionListener(this); // 对.按钮添加监听事件
setContentPane(pane);
pack(); // 初始化窗体大小为正好盛放所有按钮
}
// 各个按钮触发的事件
public void actionPerformed(ActionEvent e) {
/*
* 如果是点击数字按钮那么先要判断是否在此之前点击了+、-、*、/、=,如果是那么com=true 如果没有com=
* false;或者是否点击数字键,如果是i = 1,如果没有 i = 0;
*/
if (e.getSource() == number_key.one) {
if (com || i == 0) {
result.text.setText("1");
com = false;
i = 1;
} else {
text = result.text.getText();
result.text.setText(text + "1");
}
} else if (e.getSource() == number_key.two) {
if (com || i == 0) {
result.text.setText("2");
com = false;
i = 1;
} else {
text = result.text.getText();
result.text.setText(text + "2");
}
} else if (e.getSource() == number_key.three) {
if (com || i == 0) {
result.text.setText("3");
com = false;
i = 1;
} else {
text = result.text.getText();
result.text.setText(text + "3");
}
} else if (e.getSource() == number_key.four) {
if (com || i == 0) {
result.text.setText("4");
com = false;
i = 1;
} else {
text = result.text.getText();
result.text.setText(text + "4");
}
} else if (e.getSource() == number_key.five) {
if (com || i == 0) {
result.text.setText("5");
com = false;
i = 1;
} else {
text = result.text.getText();
result.text.setText(text + "5");
}
} else if (e.getSource() == number_key.six) {
if (com || i == 0) {
result.text.setText("6");
com = false;
i = 1;
} else {
text = result.text.getText();
result.text.setText(text + "6");
}
} else if (e.getSource() == number_key.seven) {
if (com || i == 0) {
result.text.setText("7");
com = false;
i = 1;
} else {
text = result.text.getText();
result.text.setText(text + "7");
}
} else if (e.getSource() == number_key.eight) {
if (com || i == 0) {
result.text.setText("8");
com = false;
i = 1;
} else {
text = result.text.getText();
result.text.setText(text + "8");
}
} else if (e.getSource() == number_key.nine) {
if (com || i == 0) {
result.text.setText("9");
com = false;
i = 1;
} else {
text = result.text.getText();
result.text.setText(text + "9");
}
}
/*
* 对于0这个按钮有一定的说法,在程序里不会出现如00000这样的情况,加了判断条件就是
* 如果text中的数值=0就要判断在这个数值中是否有.存在?如果有那么就在原来数值基础之上添 加0;否则保持原来的数值不变
*/
else if (e.getSource() == number_key.zero) { // result.text.getText()是得到text里内容的意思
if (com || i == 0) {
result.text.setText("0");
com = false;
i = 1;
} else {
text = result.text.getText();
if (Float.parseFloat(text) > 0 || Float.parseFloat(text) < 0) { // Float.parseFloat(text)就是类型转换了,下面都是一样
result.text.setText(text + "0");
} else {
if (text.trim().indexOf(".") == -1) {
result.text.setText(text);
} else {
result.text.setText(text + "0");
}
}
}
} else if (e.getSource() == number_key.ce) {
result.text.setText("0");
i = 0;
com = true;
// text = "";
defbutton = 0;
}
/*
* 本程序不会让一个数值中出现2个以上的小数点.具体做法是:判断是否已经存在.存在就不添加, 不存在就添加.
*/
else if (e.getSource() == number_key.point) {
if (com || i == 0) {
result.text.setText("0.");
com = false;
i = 1;
} else {
text = result.text.getText();
if (text.trim().indexOf(".") == -1) {
result.text.setText(text + ".");
} else {
result.text.setText(text);
}
}
} // 获得点击+之前的数值
else if (e.getSource() == number_key.plus) {
com = true;
i = 0;
defbutton = Double.parseDouble(result.text.getText());
symbol = 1;
} // 获得点击-之前的数值
else if (e.getSource() == number_key.sub) {
com = true;
i = 0;
defbutton = Double.parseDouble(result.text.getText());
symbol = 2;
} // 获得点击*之前的数值
else if (e.getSource() == number_key.mul) {
com = true;
i = 0;
defbutton = Double.parseDouble(result.text.getText());
System.out.println(defbutton);
symbol = 3;
} // 获得点击/之前的数值
else if (e.getSource() == number_key.div) {
com = true;
i = 0;
defbutton = Double.parseDouble(result.text.getText());
symbol = 4;
} else if (e.getSource() == number_key.equal) {
switch (symbol) {
case 1: { // 计算加法
double ad = defbutton
+ Double.parseDouble(result.text.getText());
result.text.setText(ad + "");
i = 0;
text = "";
break;
}
case 2: { // 计算减法
double ad = defbutton
- Double.parseDouble(result.text.getText());
result.text.setText(String.valueOf(ad));
i = 0;
text = "";
break;
}
case 3: { // 计算乘法
double ad = defbutton
* Double.parseDouble(result.text.getText());
result.text.setText(ad + "");
i = 0;
text = "";
break;
}
case 4: { // 计算除法
double ad = defbutton
/ Double.parseDouble(result.text.getText());
result.text.setText(ad + "");
i = 0;
text = "";
break;
}
}
System.out.println(com);
}
System.out.println(result.text.getText());
}
@SuppressWarnings("deprecation")
public static void main(String[] args) {
Jisuanqi loveyou = new Jisuanqi();
loveyou.show();
}
}
// 计算器数字按钮定义面板
class Number_Key extends JPanel {
/**
*
*/
private static final long serialVersionUID = 1L;
JButton zero = new JButton("0"); // 数字键0
JButton one = new JButton("1"); // 数字键1
JButton two = new JButton("2"); // 数字键2
JButton three = new JButton("3"); // 数字键3
JButton four = new JButton("4"); // 数字键4
JButton five = new JButton("5"); // 数字键5
JButton six = new JButton("6"); // 数字键6
JButton seven = new JButton("7"); // 数字键7
JButton eight = new JButton("8"); // 数字键8
JButton nine = new JButton("9"); // 数字键9
JButton plus = new JButton("+");
JButton sub = new JButton("-");
JButton mul = new JButton("*");
JButton div = new JButton("/");
JButton equal = new JButton("=");
JButton ce = new JButton("清零"); // 置零键
JButton point = new JButton(".");
Number_Key() {
setLayout(new GridLayout(4, 4, 1, 1)); // 定义布局管理器为网格布局
setBackground(Color.blue); // 设置背景颜色
// 添加按钮
add(one);
add(two);
add(three);
add(four);
add(five);
add(six);
add(seven);
add(eight);
add(nine);
add(zero);
add(plus);
add(sub);
add(mul);
add(div);
add(point);
add(equal);
add(ce);
}
}
// 计算器显示结果的窗体
class Result extends JPanel {
/**
*
*/
private static final long serialVersionUID = 1L;
// text先是输入和结果
JTextField text = new JTextField("0");
@SuppressWarnings("deprecation")
Result() { // 讲输入的数字或得到的结果在text的右边显示
text.setHorizontalAlignment(SwingConstants.RIGHT);
text.enable(false); // 文本框不能编辑
setLayout(new BorderLayout()); // 设定布局管理器边框布局
add(text, BorderLayout.CENTER); // text放置在窗体的中间
}
}

F. 用java编程加减乘除计算器

刚好用设计模式(简单工厂模式)编写了一个计算器。

packagecom.medavis.simplefactory.ui;

importjava.util.Scanner;

importcom.medavis.simplefactory.operate.OperatorFactory;

publicclassCaculatorUI{

privatestaticScannersc;

publicstaticvoidmain(String[]args){

try{
System.out.println("Pleaseinputanumber:");

sc=newScanner(System.in);

longfirst=sc.nextLong();

System.out.println("(+-*/):");

sc=newScanner(System.in);

Stringoperator=sc.nextLine();

System.out.println("Pleaseinputanumber:");

sc=newScanner(System.in);

longsecond=sc.nextLong();

OperatorFactoryopf=newOperatorFactory();

System.out.println(first+operator+second+"="+opf.getOperator(operator).getResult(first,second));

}catch(Exceptione){

System.out.println("Yourinputiswrong!");

}
}
}packagecom.medavis.simplefactory.operate;


{

@Override
publiclonggetResult(longfirst,longsecond){

returnfirst+second;

}
}
packagecom.medavis.simplefactory.operate;


{

@Override
publiclonggetResult(longfirst,longsecond){

returnfirst/second;

}
}

packagecom.medavis.simplefactory.operate;


publicclassOperatorFactory{

publicOperatorgetOperator(Stringoperator)throwsException{
switch(operator){
case"+":
returnnewOperatorAdd();
case"-":
returnnewOperatorSub();
case"*":
returnnewOperatorMul();
case"/":
returnnewOperatorDiv();
default:
thrownewException();
}
}

}


packagecom.medavis.simplefactory.operate;


{

@Override
publiclonggetResult(longfirst,longsecond){

returnfirst*second;

}
}

packagecom.medavis.simplefactory.operate;


{

@Override
publiclonggetResult(longfirst,longsecond){

returnfirst-second;

}
}


G. java 实现一个简单的计算器,能做100以内的加减乘除

网上找的,如果你是要求的这样的,自己写也要好一会:

import java.awt.*;
import java.awt.event.*;

public class Calculator {

private Frame f;
private TextField tf = new TextField(30);
private long result;
private boolean append = false;
private Button[] btn = new Button[15];
private char operator = '=';

public static void main(String[] args) {
new Calculator().go();
}

public Calculator() {
initComponent();
}

private void initComponent() {
f = new Frame("Java Calculator");
f.setLayout(new BorderLayout()); // The frame uses BorderLayout
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent evt) {
System.exit(0);
}
});

Panel centerPanel = new Panel();
centerPanel.setLayout(new GridLayout(5, 3)); // The panel uses GridLayout

NumberListener nl = new NumberListener();
OperatorListener ol = new OperatorListener();

btn[10] = new Button("+");
btn[11] = new Button("-");
btn[12] = new Button("*");
btn[13] = new Button("/");
btn[14] = new Button("=");

for (int i = 0; i <= 9; i++) {
btn[i] = new Button(String.valueOf(i));
centerPanel.add(btn[i]);
btn[i].addActionListener(nl);
if (i % 2 == 1) {
centerPanel.add(btn[(i + 19) / 2]);
btn[(i + 19) / 2].addActionListener(ol);
}
}
f.add(centerPanel, BorderLayout.CENTER);

Panel northPanel = new Panel();

tf.setEditable(false);
northPanel.add(tf);
f.add(northPanel, BorderLayout.NORTH);
}

public void go() {
f.pack();
f.setVisible(true);
}

/**
* 采用成员内部类方式,实现监听器接口,方便访问主类内类内部成员。 此类负责数字按钮Action事件监听和处理
*/
class NumberListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (!append) {
tf.setText("");
append = true;
}
String s = tf.getText();
s += e.getActionCommand();
tf.setText(s);
if (!btn[10].isEnabled()) {
for (int i = 10; i <= 14; i++)
btn[i].setEnabled(true);
}
}
}

/**
* 成员内部类,负责操作符按钮的事件处理
*/
class OperatorListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (!append)
return;
for (int i = 10; i <= 14; i++)
btn[i].setEnabled(false);
String s = tf.getText();
long num = Long.parseLong(s);// get the number of textfield
append = false; // set append
switch (operator) {
case '+':
result += num;
break;
case '-':
result -= num;
break;
case '*':
result *= num;
break;
case '/': {
if (num == 0)
result = 0;
else
result /= num;
break;
}
case '=':
result = num;
break;
}
tf.setText(String.valueOf(result));
// set the value of result to textfield
String op = e.getActionCommand();
operator = op.charAt(0); // set operator
}
}
}

H. java加减乘除计算器界面编程

来源:Code Wizards HQ

智能观 编译

孩子想学编码的话,有很多方法可以展开学习。可以让他们学着构建视频游戏、创建动画、开发移动应用程序和搭建网站。不管孩子喜欢哪种形式,都有大量的编码书供他们快速学起来!

但是,怎么才能找到一本好的儿童编码书呢?


I. 如何使用Java对象语言编写一个加减乘除计算器要有代码

下面文件名要为:JiSuanQi.java

importjava.awt.*;

importjava.awt.event.*;

publicclassJiSuanQi

{

Strings="",s1=null,s2=null;

Framef=newFrame("计算器");

TextFieldtf=newTextField(30);

Panelp1=newPanel();

Panelp2=newPanel();

Panelp3=newPanel();

Buttonbt1=newButton("=");

Buttonbt2=newButton("删除");

Button[]bt=newButton[16];

intid=0;

publicstaticvoidmain(String[]args)

{

newJiSuanQi().init();

}

publicvoidinit()

{

f.setBackground(newColor(85,247,253));

f.setLayout(newBorderLayout(4,4));

p2.setLayout(newGridLayout(4,4,4,4));

p3.setLayout(newBorderLayout(4,4));

f.setResizable(false);

f.add(p1,BorderLayout.NORTH);

f.add(p2);

p3.add(bt2,BorderLayout.NORTH);

p3.add(bt1);

p1.add(tf);

f.add(p3,BorderLayout.EAST);

String[]b={"1","2","3","+","4","5","6","-","7","8","9","*","0",".","复位","/"};

for(inti=0;i<16;i++)

{

bt[i]=newButton(b[i]);

p2.add(bt[i]);

}

bt[0].setForeground(Color.blue);

bt[1].setForeground(Color.blue);

bt[2].setForeground(Color.blue);

bt[4].setForeground(Color.blue);

bt[5].setForeground(Color.blue);

bt[6].setForeground(Color.blue);

bt[8].setForeground(Color.blue);

bt[9].setForeground(Color.blue);

bt[10].setForeground(Color.blue);

bt[12].setForeground(Color.blue);

bt[13].setForeground(Color.blue);

bt[3].setForeground(Color.red);

bt[7].setForeground(Color.red);

bt[11].setForeground(Color.red);

bt[15].setForeground(Color.red);

bt[14].setForeground(Color.red);

bt1.setForeground(Color.red);

bt2.setForeground(Color.red);

f.pack();

f.setVisible(true);

f.addWindowListener(newWindowAdapter()

{

publicvoidwindowClosing(WindowEvente)

{

System.exit(0);

}

}

);

bt[0].addActionListener(newActionListener()

{

publicvoidactionPerformed(ActionEvente)

{

s+=1;

s2+=1;

tf.setText(s);

}

}

);

bt[1].addActionListener(newActionListener()

{

publicvoidactionPerformed(ActionEvente)

{

s+=2;

s2+=2;

tf.setText(s);

}

}

);

bt[2].addActionListener(newActionListener()

{

publicvoidactionPerformed(ActionEvente)

{

s+=3;

s2+=3;

tf.setText(s);

}

}

);

bt[4].addActionListener(newActionListener()

{

publicvoidactionPerformed(ActionEvente)

{

s+=4;

s2+=4;

tf.setText(s);

}

}

);

bt[5].addActionListener(newActionListener()

{

publicvoidactionPerformed(ActionEvente)

{

s+=5;

s2+=5;

tf.setText(s);

}

}

);

bt[6].addActionListener(newActionListener()

{

publicvoidactionPerformed(ActionEvente)

{

s+=6;

s2+=6;

tf.setText(s);

}

}

);

bt[8].addActionListener(newActionListener()

{

publicvoidactionPerformed(ActionEvente)

{

s+=7;

s2+=7;

tf.setText(s);

}

}

);

bt[9].addActionListener(newActionListener()

{

publicvoidactionPerformed(ActionEvente)

{

s+=8;

s2+=8;

tf.setText(s);

}

}

);

bt[10].addActionListener(newActionListener()

{

publicvoidactionPerformed(ActionEvente)

{

s+=9;

s2+=9;

tf.setText(s);

}

}

);

bt[12].addActionListener(newActionListener()

{

publicvoidactionPerformed(ActionEvente)

{

s+=0;

s2+=0;

tf.setText(s);

}

}

);

bt[13].addActionListener(newActionListener()

{

publicvoidactionPerformed(ActionEvente)

{

s+='.';

s2+='.';

tf.setText(s);

}

}

);

bt[3].addActionListener(newActionListener()

{

publicvoidactionPerformed(ActionEvente)

{

s1=s;

s+='+';

id=1;

s2="";

tf.setText(s);

}

}

);

bt[7].addActionListener(newActionListener()

{

publicvoidactionPerformed(ActionEvente)

{

s1=s;

s+='-';

id=2;

s2="";

tf.setText(s);

}

}

);

bt[11].addActionListener(newActionListener()

{

publicvoidactionPerformed(ActionEvente)

{

s1=s;

s+='*';

id=3;

s2="";

tf.setText(s);

}

}

);

bt[14].addActionListener(newActionListener()

{

publicvoidactionPerformed(ActionEvente)

{

s="";

s2="";

tf.setText(s);

}

}

);

bt[15].addActionListener(newActionListener()

{

publicvoidactionPerformed(ActionEvente)

{

s1=s;

s+='/';

id=4;

s2="";

tf.setText(s);

}

}

);

bt1.addActionListener(newActionListener()

{

publicvoidactionPerformed(ActionEvente)

{

if(id<1);

else{

s+='=';

doublea=Double.parseDouble(s1);

doubleb=Double.parseDouble(s2);

doublec=0;

switch(id)

{

case1:c=a+b;break;

case2:c=a-b;break;

case3:c=a*b;break;

case4:c=a/b;break;

}

s+=c;

tf.setText(s);

}

s="";s1="";s2="";id=0;

}

}

);

bt2.addActionListener(newActionListener()

{

publicvoidactionPerformed(ActionEvente)

{

char[]c1;

char[]c2=newchar[s.length()-1];

c1=s.toCharArray();

for(inti=0;i<s.length()-1;i++)

c2[i]=c1[i];

s=s.valueOf(c2);

if(id<1)

{

s1=s;

}

if(s2.length()>=1)

{

char[]c3;

char[]c4=newchar[s2.length()-1];

c3=s2.toCharArray();

for(inti=0;i<s2.length()-1;i++)

c4[i]=c3[i];

s2=s2.valueOf(c4);

}

tf.setText(s);

}

}

);

}

}

J. 用JAVA编写一个计算器

importjava.awt.BorderLayout;

importjava.awt.Color;

importjava.awt.GridLayout;

importjava.awt.event.ActionEvent;

importjava.awt.event.ActionListener;

importjavax.swing.ImageIcon;

importjavax.swing.JButton;

importjavax.swing.JFrame;

importjavax.swing.JPanel;

importjavax.swing.JTextField;

importjavax.swing.SwingConstants;

{

/**

*

*/

=1L;

Resultresult=newResult();//定义text的面板

Number_Keynumber_key=newNumber_Key();//定义按钮面板

//当点击按钮+、-、*、/时,com=true

booleancom=false;

//当i=0时说明是我们第一次输入,字符串text不会累加

inti=0;

//存放text的内容

Stringtext="";

//存放点击按钮+、-、*、/之前的数值

doubledefbutton=0;

//+、-、*、/的代号分别为1,2,3,4

intsymbol=0;

//构造函数

Jisuanqi(){

super("WangJiao");//设定标题

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//设定关闭窗体时退出程序

JPanelpane=newJPanel();//定义主面板

pane.setLayout(newBorderLayout());

setBounds(380,220,30,80);//前两个参数是在屏幕上显示的坐标,后两个是大小

//替换图标

ImageIconicon=newImageIcon("F:1.GIF");

//Jisuanqi.class.getResource("APPLE.GIF")

//);

setIconImage(icon.getImage());

pane.add(result,BorderLayout.NORTH);

pane.add(number_key,BorderLayout.CENTER);

pane.add(number_key.equal,BorderLayout.SOUTH);

number_key.one.addActionListener(this);//对1按钮添加监听事件

number_key.two.addActionListener(this);//对2按钮添加监听事件

number_key.three.addActionListener(this);//对3按钮添加监听事件

number_key.four.addActionListener(this);//对4按钮添加监听事件

number_key.five.addActionListener(this);//对5按钮添加监听事件

number_key.six.addActionListener(this);//对6按钮添加监听事件

number_key.seven.addActionListener(this);//对7按钮添加监听事件

number_key.eight.addActionListener(this);//对8按钮添加监听事件

number_key.nine.addActionListener(this);//对9按钮添加监听事件

number_key.zero.addActionListener(this);//对0按钮添加监听事件

number_key.ce.addActionListener(this);//对置零按钮添加监听事件

number_key.plus.addActionListener(this);//对+按钮添加监听事件

number_key.equal.addActionListener(this);//对=按钮添加监听事件

number_key.sub.addActionListener(this);//对-按钮添加监听事件

number_key.mul.addActionListener(this);//对*按钮添加监听事件

number_key.div.addActionListener(this);//对/按钮添加监听事件

number_key.point.addActionListener(this);//对.按钮添加监听事件

setContentPane(pane);

pack();//初始化窗体大小为正好盛放所有按钮

}

//各个按钮触发的事件

publicvoidactionPerformed(ActionEvente){

/*

*如果是点击数字按钮那么先要判断是否在此之前点击了+、-、*、/、=,如果是那么com=true如果没有com=

*false;或者是否点击数字键,如果是i=1,如果没有i=0;

*/

if(e.getSource()==number_key.one){

if(com||i==0){

result.text.setText("1");

com=false;

i=1;

}else{

text=result.text.getText();

result.text.setText(text+"1");

}

}elseif(e.getSource()==number_key.two){

if(com||i==0){

result.text.setText("2");

com=false;

i=1;

}else{

text=result.text.getText();

result.text.setText(text+"2");

}

}elseif(e.getSource()==number_key.three){

if(com||i==0){

result.text.setText("3");

com=false;

i=1;

}else{

text=result.text.getText();

result.text.setText(text+"3");

}

}elseif(e.getSource()==number_key.four){

if(com||i==0){

result.text.setText("4");

com=false;

i=1;

}else{

text=result.text.getText();

result.text.setText(text+"4");

}

}elseif(e.getSource()==number_key.five){

if(com||i==0){

result.text.setText("5");

com=false;

i=1;

}else{

text=result.text.getText();

result.text.setText(text+"5");

}

}elseif(e.getSource()==number_key.six){

if(com||i==0){

result.text.setText("6");

com=false;

i=1;

}else{

text=result.text.getText();

result.text.setText(text+"6");

}

}elseif(e.getSource()==number_key.seven){

if(com||i==0){

result.text.setText("7");

com=false;

i=1;

}else{

text=result.text.getText();

result.text.setText(text+"7");

}

}elseif(e.getSource()==number_key.eight){

if(com||i==0){

result.text.setText("8");

com=false;

i=1;

}else{

text=result.text.getText();

result.text.setText(text+"8");

}

}elseif(e.getSource()==number_key.nine){

if(com||i==0){

result.text.setText("9");

com=false;

i=1;

}else{

text=result.text.getText();

result.text.setText(text+"9");

}

}

/*

*对于0这个按钮有一定的说法,在我的程序里不会出现如00000这样的情况,我加了判断条件就是

*如果text中的数值=0就要判断在这个数值中是否有.存在?如果有那么就在原来数值基础之上添加0;否则保持原来的数值不变

*/

elseif(e.getSource()==number_key.zero){//result.text.getText()是得到text里内容的意思

if(com||i==0){

result.text.setText("0");

com=false;

i=1;

}else{

text=result.text.getText();

if(Float.parseFloat(text)>0||Float.parseFloat(text)<0){//Float.parseFloat(text)就是类型转换了,下面都是一样

result.text.setText(text+"0");

}else{

if(text.trim().indexOf(".")==-1){

result.text.setText(text);

}else{

result.text.setText(text+"0");

}

}

}

}elseif(e.getSource()==number_key.ce){

result.text.setText("0");

i=0;

com=true;

//text="";

defbutton=0;

}

/*

*本程序不会让一个数值中出现2个以上的小数点.具体做法是:判断是否已经存在.存在就不添加,不存在就添加.

*/

elseif(e.getSource()==number_key.point){

if(com||i==0){

result.text.setText("0.");

com=false;

i=1;

}else{

text=result.text.getText();

if(text.trim().indexOf(".")==-1){

result.text.setText(text+".");

}else{

result.text.setText(text);

}

}

}//获得点击+之前的数值

elseif(e.getSource()==number_key.plus){

com=true;

i=0;

defbutton=Double.parseDouble(result.text.getText());

symbol=1;

}//获得点击-之前的数值

elseif(e.getSource()==number_key.sub){

com=true;

i=0;

defbutton=Double.parseDouble(result.text.getText());

symbol=2;

}//获得点击*之前的数值

elseif(e.getSource()==number_key.mul){

com=true;

i=0;

defbutton=Double.parseDouble(result.text.getText());

System.out.println(defbutton);

symbol=3;

}//获得点击/之前的数值

elseif(e.getSource()==number_key.div){

com=true;

i=0;

defbutton=Double.parseDouble(result.text.getText());

symbol=4;

}elseif(e.getSource()==number_key.equal){

switch(symbol){

case1:{//计算加法

doublead=defbutton

+Double.parseDouble(result.text.getText());

result.text.setText(ad+"");

i=0;

text="";

break;

}

case2:{//计算减法

doublead=defbutton

-Double.parseDouble(result.text.getText());

result.text.setText(String.valueOf(ad));

i=0;

text="";

break;

}

case3:{//计算乘法

doublead=defbutton

*Double.parseDouble(result.text.getText());

result.text.setText(ad+"");

i=0;

text="";

break;

}

case4:{//计算除法

doublead=defbutton

/Double.parseDouble(result.text.getText());

result.text.setText(ad+"");

i=0;

text="";

break;

}

}

System.out.println(com);

}

System.out.println(result.text.getText());

}

@SuppressWarnings("deprecation")

publicstaticvoidmain(String[]args){

Jisuanqiloveyou=newJisuanqi();

loveyou.show();

}

}

//计算器数字按钮定义面板

classNumber_KeyextendsJPanel{

/**

*

*/

=1L;

JButtonzero=newJButton("0");//数字键0

JButtonone=newJButton("1");//数字键1

JButtontwo=newJButton("2");//数字键2

JButtonthree=newJButton("3");//数字键3

JButtonfour=newJButton("4");//数字键4

JButtonfive=newJButton("5");//数字键5

JButtonsix=newJButton("6");//数字键6

JButtonseven=newJButton("7");//数字键7

JButtoneight=newJButton("8");//数字键8

JButtonnine=newJButton("9");//数字键9

JButtonplus=newJButton("+");

JButtonsub=newJButton("-");

JButtonmul=newJButton("*");

JButtondiv=newJButton("/");

JButtonequal=newJButton("=");

JButtonce=newJButton("清零");//置零键

JButtonpoint=newJButton(".");

Number_Key(){

setLayout(newGridLayout(4,4,1,1));//定义布局管理器为网格布局

setBackground(Color.blue);//设置背景颜色

//添加按钮

add(one);

add(two);

add(three);

add(four);

add(five);

add(six);

add(seven);

add(eight);

add(nine);

add(zero);

add(plus);

add(sub);

add(mul);

add(div);

add(point);

add(equal);

add(ce);

}

}

//计算器显示结果的窗体

classResultextendsJPanel{

/**

*

*/

=1L;

//text先是输入和结果

JTextFieldtext=newJTextField("0");

@SuppressWarnings("deprecation")

Result(){//讲输入的数字或得到的结果在text的右边显示

text.setHorizontalAlignment(SwingConstants.RIGHT);

text.enable(false);//文本框不能编辑

setLayout(newBorderLayout());//设定布局管理器边框布局

add(text,BorderLayout.CENTER);//text放置在窗体的中间

}

}

直接复制保存成Jisuanqi.java可以直接运行了

阅读全文

与java加法计算器相关的资料

热点内容
非科班程序员自学 浏览:797
压缩泡沫鞋底底材 浏览:217
程序员职场第一课2正确的沟通 浏览:677
遇到不合法app应该怎么办 浏览:90
汇编程序编译后的文件 浏览:77
大智慧均线源码 浏览:371
单片机排阻的作用 浏览:213
滴滴金融app被下架如何还款 浏览:210
jpg转换成pdf免费软件 浏览:741
范里安pdf 浏览:443
伪造pdf 浏览:75
能删除android文件夹吗 浏览:446
LINUX使用V2ray 浏览:797
找人帮忙注册app推广是什么 浏览:820
独立服务器如何恢复初始化 浏览:11
优秀到不能被忽视pdf 浏览:316
导游程序员家政 浏览:586
22乘28的快速算法 浏览:338
软通动力程序员节2021 浏览:846
安卓系统如何卸载安装包 浏览:870