用java编写一个简单计算器
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了用java编写一个简单计算器相关的知识,希望对你有一定的参考价值。
编写一个GUI程序,利用第一和第二个文本框分别输入两个整数,在单击运算符按钮时,则在第一和第二个文本框之间显示运算符;单击‘=’按钮,则在第三个文本框中显示第一和第二个文本框的运算结果。
就按照我给的题目,写出图片一样的程序
/*
* @(#)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 你这是样本吗?不是已经写好了?追问
哪有?那些都是很复杂的,我并不需要那么复杂的
追答你什么要求
追问就按照我给的那个要求做就可以了
如何使用JS编写一个简单的计算器
参考技术A js部分var num=0,result=0,numshow="0";
var operate=0; //判断输入状态的标志
var calcul=0; //判断计算状态的标志
var quit=0; //防止重复按键的标志
function command(num)
var str=String(document.calculator.numScreen.value); //获得当前显示数据
str=(str!="0") ? ((operate==0) ? str : "") : ""; //如果当前值不是"0",且状态为0,则返回当前值,否则返回空值;
str=str + String(num); //给当前值追加字符
document.calculator.numScreen.value=str; //刷新显示
operate=0; //重置输入状态
quit=0; //重置防止重复按键的标志
function dzero()
var str=String(document.calculator.numScreen.value);
str=(str!="0") ? ((operate==0) ? str + "00" : "0") : "0"; //如果当前值不是"0",且状态为0,则返回当str+"00",否则返回"0";
document.calculator.numScreen.value=str;
operate=0;
function dot()
var str=String(document.calculator.numScreen.value);
str=(str!="0") ? ((operate==0) ? str : "0") : "0"; //如果当前值不是"0",且状态为0,则返回当前值,否则返回"0";
for(i=0; i<=str.length;i++) //判断是否已经有一个点号
if(str.substr(i,1)==".") return false; //如果有则不再插入
str=str + ".";
document.calculator.numScreen.value=str;
operate=0;
function del() //退格
var str=String(document.calculator.numScreen.value);
str=(str!="0") ? str : "";
str=str.substr(0,str.length-1);
str=(str!="") ? str : "0";
document.calculator.numScreen.value=str;
function clearscreen() //清除数据
num=0;
result=0;
numshow="0";
document.calculator.numScreen.value="0";
function plus() //加法
calculate(); //调用计算函数
operate=1; //更改输入状态
calcul=1; //更改计算状态为加
function minus() //减法
calculate();
operate=1;
calcul=2;
function times() //乘法
calculate();
operate=1;
calcul=3;
function divide() //除法
calculate();
operate=1;
calcul=4;
function persent() //求余
calculate();
operate=1;
calcul=5;
function equal()
calculate(); //等于
operate=1;
num=0;
result=0;
numshow="0";
//
function calculate()
numshow=Number(document.calculator.numScreen.value);
if(num!=0 && quit!=1) //判断前一个运算数是否为零以及防重复按键的状态
switch(calcul) //判断要输入状态
case 1:result=num+numshow;break; //计算"+"
case 2:result=num-numshow;break; //计算"-"
case 3:result=num*numshow;break;
case 4:if(numshow!=0)result=num/numshow;elsedocument.getElementById("note").innerHTML="被除数不能为零!"; setTimeout(clearnote,4000) break;
case 5:result=num%numshow;break;
quit=1; //避免重复按键
else
result=numshow;
numshow=String(result);
document.calculator.numScreen.value=numshow;
num=result; //存储当前值
function clearnote() //清空提示
document.getElementById("note").innerHTML="";
html部分:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>写给新手:js表单操作(四) 简单计算器(二)</title>
<style type="text/css">
body
font-size:12px;
font-family:Arial, Georgia, "Times New Roman", Times, serif;
color:#555;
text-align:center;
background-color:#e2e2e2;
h6
margin:0;
font-size:12px;
#calculator
width:240px;
height:auto;
overflow:hidden;
margin:10px auto;
border:#fff 1px solid;
padding-bottom:10px;
background-color:#f2f2f2;
#calculator div
clear:both;
#calculator ul
padding:0;
margin:5px 14px;
border:#fff 1px solid;
height:auto;
overflow:hidden
#calculator li
list-style:none;
float:left;
width:32px;
height:32px;
margin:5px;
display:inline;
line-height:32px;
font-size:14px;
background-color:#eaeaea;
#calculator li.tool
background-color:#e2e2e2;
#calculator li:hover
background-color:#f9f9f9;
cursor:pointer;
#calculator li:active
background-color:#fc0;
cursor:pointer;
#calculator li.tool:active
background-color:#d8e8ff;
cursor:pointer;
#calcu-head
text-align:left;
padding:10px 15px 5px;
span.imyeah
float:right;
color:#ccc;
span.imyeah a
color:#ccc;
.screen
width:200px;
height:24px;
line-height:24px;
padding:4px;
border:#e6e6e6 1px solid;
border-bottom:#f2f2f2 1px solid;
border-right:#f2f2f2 1px solid;
margin:10px auto;
direction:ltr;
text-align:right;
font-size:16px;
color:#999;
#calcu-foot
text-align:left;
padding:10px 15px 5px;
height:auto;
overflow:hidden;
span#note
float:left;
width:210px;
height:auto;
overflow:hidden;
color:red;
span.welcome
clear:both;
color:#999;
span.welcome a
float:right;
color:#999;
</style>
<script language="javascript">
//此处插入上面的js代码
</script>
</head>
<body>
<div id="calculator">
<div id="calcu-head"><span class="imyeah">© <a href="http://www.cnblogs.com/imyeah/" target="_blank">I'm Yeah!</a></span><h6>简单的计算器</h6></div>
<form name="calculator" action="" method="get">
<div id="calcu-screen">
<!--配置显示窗口,使用onfocus="this.blur();"避免键盘输入-->
<input type="text" name="numScreen" class="screen" value="0" onfocus="this.blur();" />
</div>
<div id="calcu-btn">
<ul> <!--配置按钮-->
<li onclick="command(7)">7</li>
<li onclick="command(8)">8</li>
<li onclick="command(9)">9</li>
<li class="tool" onclick="del()">←</li>
<li class="tool" onclick="clearscreen()">C</li>
<li onclick="command(4)">4</li>
<li onclick="command(5)">5</li>
<li onclick="command(6)">6</li>
<li class="tool" onclick="times()">×</li>
<li class="tool" onclick="divide()">÷</li>
<li onclick="command(1)">1</li>
<li onclick="command(2)">2</li>
<li onclick="command(3)">3</li>
<li class="tool" onclick="plus()">+</li>
<li class="tool" onclick="minus()">-</li>
<li onclick="command(0)">0</li>
<li onclick="dzero()">00</li>
<li onclick="dot()">.</li>
<li class="tool" onclick="persent()">%</li>
<li class="tool" onclick="equal()">=</li>
</ul>
</div>
<div id="calcu-foot">
<span id="note"></span>
<span class="welcome">欢迎使用javascript计算器!<a href="http://www.cnblogs.com/imyeah" target="_blank">反馈</a></span>
</div>
</form>
</div>
</body>
</html>
以上是关于用java编写一个简单计算器的主要内容,如果未能解决你的问题,请参考以下文章