java:编写一个计算器小程序,要求可以做加减乘除运算
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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();
参考技术A kankan我的
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.math.BigDecimal;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class TestCalc implements ActionListener
JFrame jf = new JFrame("计算器");
JPanel jp = new JPanel();
JTextField jtf = new JTextField("0.", 200);
JButton[] jb = new JButton[20];
private int tag = 0;
private double a;
private double b;
private String operator;
StringBuilder sb1 = new StringBuilder();
StringBuilder sb2 = new StringBuilder();
public TestCalc()
jf.add(jtf, BorderLayout.NORTH);
// jtf.requestFocus();
jtf.setEditable(false);
jtf.setCaretPosition(jtf.getText().length() - 1);
jf.add(jp);
jp.setLayout(new GridLayout(5, 4, 4, 4));
String[] str = "Back", "CE", "C", "+", "7", "8", "9", "-", "4", "5",
"6", "*", "1", "2", "3", "/", "0", "+/-", ".", "=" ;
int i = 0;
for (i = 0; i < str.length; i++)
jb[i] = new JButton(str[i]);
jp.add(jb[i]);
jb[i].addActionListener(this);
jf.setSize(300, 240);
// jf.setLocation(300,200);
jf.setLocationRelativeTo(null);
jf.setVisible(true);
// jf.pack();//自动调整大小;
jf.setResizable(false);// 不允许别人调大小;
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
public static void main(String[] args)
TestCalc tc = new TestCalc();
public void actionPerformed(ActionEvent e)
String command = e.getActionCommand();
if (command.matches("^[[0-9].]$"))
if (tag == 0)
sb1.append(command);
jtf.setText(sb1.substring(0));
else
sb2.append(command);
jtf.setText(sb2.substring(0));
else if (command.matches("^[-/*+]$"))
tag = 1;
operator = command;
else
if (command.matches("="))
String str1 = sb1.substring(0);
String str2 = sb2.substring(0);
if (str1 == null)
a = 0.0;
else
a = Double.parseDouble(str1);
if (str2 == null)
b = 0.0;
else
b = Double.parseDouble(str2);
if (operator.equals("+"))
jtf.setText("" + (a + b));
else if (operator.equals("-"))
BigDecimal bd1 = new BigDecimal(Double.toString(a)); // 必须使用String做参数才可以精确运算
BigDecimal bd2 = new BigDecimal(Double.toString(b));
Double yu1 = bd1.subtract(bd2).doubleValue();
jtf.setText("" + (yu1));
else if (operator.equals("*"))
jtf.setText("" + (a * b));
else if (operator.equals("/"))
BigDecimal bd1 = new BigDecimal(Double.toString(a)); // 必须使用String做参数才可以精确运算
BigDecimal bd2 = new BigDecimal(Double.toString(b));
Double yu1 = bd1.divide(bd2).doubleValue();
jtf.setText("" + yu1);
tag = 0;
sb1.delete(0, sb1.length());
sb2.delete(0, sb2.length());
else if (command.matches("C"))
tag = 0;
sb1.delete(0, sb1.length());
sb2.delete(0, sb2.length());
jtf.setText("0.");
jtf.setCaretPosition(jtf.getText().length() - 1);
else if (command.matches("CE"))
tag = 0;
sb2.delete(0, sb2.length());
jtf.setText(sb1.substring(0));
else if (command.matches("Back")) //Back功能键的实现;
if (tag == 0)
sb1.deleteCharAt(sb1.length() - 1);
jtf.setText(sb1.substring(0));
else
sb2.deleteCharAt(sb2.length() - 1);
jtf.setText(sb2.substring(0));
else if (command.matches("\\+/-"))
if (tag == 0)
if(sb1.substring(0,1).equals("-"))
sb1.replace(0,1,"+");
else
sb1.insert(0, "-");
jtf.setText(sb1.substring(0));
else
if(sb2.substring(0,1).equals("-"))
sb2.replace(0,1,"+");
else
sb2.insert(0, "-");
jtf.setText(sb2.substring(0));
else
参考技术B 这是我做的小计算器,你看下,可以实现加减乘除。觉得好就采纳,谢谢啦。
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class calculate
public static void main(String[] args)
jxframe kj=new jxframe();
kj.setVisible(true);
kj.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
class jxframe extends JFrame
JTextField w;
private boolean pd;
private String bj;
private double result;
public jxframe()
setTitle("计算器");
pd=true;
bj="=";
result=0;
w=new JTextField(20);
add(w,"North");
add(new m(),"Center");
pack();
class m extends JComponent
public m()
setLayout(new GridLayout(4,4));
addbutton("7",new sz());
addbutton("8",new sz());
addbutton("9",new sz());
addbutton("/",new jx());
addbutton("4",new sz());
addbutton("5",new sz());
addbutton("6",new sz());
addbutton("*",new jx());
addbutton("1",new sz());
addbutton("2",new sz());
addbutton("3",new sz());
addbutton("+",new jx());
addbutton("0",new sz());
addbutton(".",new sz());
addbutton("=",new jx());
addbutton("-",new jx());
public void addbutton(String name,ActionListener e)
JButton an=new JButton(name);
an.addActionListener(e);
add(an);
class sz implements ActionListener
public void actionPerformed(ActionEvent e)
String sb=e.getActionCommand();
if(pd)
w.setText("");
pd=false;
w.setText(w.getText()+sb);
class jx implements ActionListener
public void actionPerformed(ActionEvent e)
String jb=e.getActionCommand();
if(pd)
jb.equals("-");
w.setText(jb);
pd=false;
else
js(Double.parseDouble(w.getText()));
bj=jb;
pd=true;
public void js(double jsb)
if(bj.equals("/")) result/=jsb;
if(bj.equals("*")) result*=jsb;
if(bj.equals("+")) result+=jsb;
if(bj.equals("-")) result-=jsb;
if(bj.equals("=")) result=jsb;
w.setText(""+result);
参考技术C 代码如下:
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Accumulator extends JFrame implements ActionListener,ItemListener
public double result=0;
static String is="+";
JTextField jt1 = new JTextField(10);
JTextField jt2 = new JTextField(10);
JTextField jt3 = new JTextField(10);
JComboBox jcb = new JComboBox();
JButton jb = new JButton("=");
public Accumulator()
JPanel jp = new JPanel();
jp.setLayout(new FlowLayout());
jcb.addItemListener(this);
jcb.addItem("+");
jcb.addItem("-");
jcb.addItem("*");
jcb.addItem("/");
jb.addActionListener(this);
jp.add(jt1);
jp.add(jcb);
jp.add(jt2);
jp.add(jb);
jp.add(jt3);
this.setTitle("简易计算器");
this.add(jp);
this.setBounds(400, 350, 500, 300);
this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
this.setVisible(true);
@Override
public void actionPerformed(ActionEvent ae)
if(ae.getSource()==jb)
if(is.equals("+"))
result =Double.parseDouble(jt1.getText())+Double.parseDouble(jt2.getText());
jt3.setText(String.valueOf(result));
if(is.equals("-"))
result =Double.parseDouble(jt1.getText())-Double.parseDouble(jt2.getText());
jt3.setText(String.valueOf(result));
if(is.equals("*"))
result =Double.parseDouble(jt1.getText())*Double.parseDouble(jt2.getText());
jt3.setText(String.valueOf(result));
if(is.equals("/"))
result =Double.parseDouble(jt1.getText())/Double.parseDouble(jt2.getText());
jt3.setText(String.valueOf(result));
public static void main(String [] args)
Accumulator ac = new Accumulator();
@Override
public void itemStateChanged(ItemEvent ie)
is =(String)ie.getItem();
java课程设计:设计一个计算器模拟程序。
功能要求:该程序显示GUI用户界面,能实现整数的加、减、乘、除四则运算。
界面要示:用图形界面实现。
发到我邮箱:1351581741@qq.com
以上是关于java:编写一个计算器小程序,要求可以做加减乘除运算的主要内容,如果未能解决你的问题,请参考以下文章
用JAVA制作一个小程序,计算两个数的加减乘除,用Applet实现
使用javafx技术编写一个计算器的程序,在计算器的界面上能进行加减乘除的操作