import javax.swing.*;//新的窗口组件包
import java.awt.*;
import java.awt.event.*;
public class Calculator extends JFrame implements ActionListener
{
private boolean dotExist, operated, equaled; // 帮助运算的布尔变量
private double storedNumber; // 目前的结果
private char lastOperator; // 表示上一运算符
private JTextField operation; // 显示栏
private JButton dot, plus, minus, multi, div, sqrt, equal, changePN, clear; // 运算符
private JButton[] numbers; // 数字
// 构造者
public Calculator()
{
setTitle("简单计算器");
// 初始化变量
dotExist = false; // 表示当前的数是否有小数点
operated = false; // 表示任意运算符是否被按下
equaled = false; // 表示等号是否被按下
storedNumber = 0;
lastOperator = '?';
// 初始化窗口变量
operation = new JTextField("0");
operation.setEditable(false); //设置文本框的可编辑性
numbers = new JButton[10];
for (int i = 0; i < 10; i++)
numbers[i] = new JButton("" + i);
dot = new JButton(".");
plus = new JButton("+");
minus = new JButton("-");
multi = new JButton("*");
div = new JButton("/");
sqrt = new JButton("√");
equal = new JButton("=");
changePN = new JButton("±");
clear = new JButton("NC");
// 将窗口物体放入窗口
GridBagLayout layout = new GridBagLayout();
getContentPane().setLayout(layout);
addComponent(layout, operation, 0, 0, 4, 1);
addComponent(layout, numbers[1], 1, 0, 1, 1);
addComponent(layout, numbers[2], 1, 1, 1, 1);
addComponent(layout, numbers[3], 1, 2, 1, 1);
addComponent(layout, numbers[4], 2, 0, 1, 1);
addComponent(layout, numbers[5], 2, 1, 1, 1);
addComponent(layout, numbers[6], 2, 2, 1, 1);
addComponent(layout, numbers[7], 3, 0, 1, 1);
addComponent(layout, numbers[8], 3, 1, 1, 1);
addComponent(layout, numbers[9], 3, 2, 1, 1);
addComponent(layout, dot, 4, 0, 1, 1);
addComponent(layout, numbers[0], 4, 1, 1, 1);
addComponent(layout, sqrt, 4, 2, 1, 1);
addComponent(layout, plus, 1, 3, 1, 1);
addComponent(layout, minus, 2, 3, 1, 1);
addComponent(layout, multi, 3, 3, 1, 1);
addComponent(layout, div, 4, 3, 1, 1);
addComponent(layout, equal, 5, 0, 2, 1);
addComponent(layout, changePN, 5, 2, 1, 1);
addComponent(layout, clear, 5, 3, 1, 1);
}
// 对按钮进行反应的方法
public void actionPerformed(ActionEvent e)
{
JButton btn = (JButton)e.getSource();
if (btn == clear)
{
operation.setText("0");
dotExist = false;
storedNumber = 0;
lastOperator = '?';
}
else if (btn == equal)
{
operate('=');
equaled = true;
}
else if (btn == plus)
{
operate('+');
equaled = false;
}
else if (btn == minus)
{
operate('-');
equaled = false;
}
else if (btn == multi)
{
operate('*');
equaled = false;
}
else if (btn == div)
{
operate('/');
equaled = false;
}
else if (btn == changePN)
{
operate('p');
operate('=');
equaled = true;
}
else if (btn == sqrt)
{
operate('s');
operate('=');
equaled = true;
}
else
{
if (equaled)
storedNumber = 0;
for (int i = 0; i < 10; i++)
if (btn == numbers[i])
{
if (operation.getText().equals("0"))
operation.setText("" + i);
else if(! operated)
operation.setText(operation.getText() + i);
else
{
operation.setText("" + i);
operated = false;
}
}
if (btn == dot && ! dotExist)
{
operation.setText(operation.getText() + ".");
dotExist = true;
}
}
}
// 进行运算的方法
private void operate(char operator)
{
double currentNumber = Double.valueOf(operation.getText()).doubleValue();
if (lastOperator == '?')
storedNumber = currentNumber;
else if (lastOperator == '+')
storedNumber += currentNumber;
else if (lastOperator == '-')
storedNumber -= currentNumber;
else if (lastOperator == '*')
storedNumber *= currentNumber;
else if (lastOperator == '/')
storedNumber /= currentNumber;
else if (lastOperator == 'p')
storedNumber *= -1;
else if (lastOperator == 's')
storedNumber = Math.sqrt(currentNumber);
else if (lastOperator == '=' && equaled)
storedNumber = currentNumber;
operation.setText("" + storedNumber);
operated = true;
lastOperator = operator;
}
// 快捷使用GridBagLayout的方法
private void addComponent(GridBagLayout layout, Component component, int row, int col, int width, int height)
{
GridBagConstraints constraints = new GridBagConstraints();
constraints.fill = GridBagConstraints.BOTH;
constraints.insets = new Insets(10, 2, 10, 2);
constraints.weightx = 100;
constraints.weighty = 100;
constraints.gridx = col;
constraints.gridy = row;
constraints.gridwidth = width;
constraints.gridheight = height;
layout.setConstraints(component, constraints);
if (component instanceof JButton)
((JButton)component).addActionListener(this);
getContentPane().add(component);
}
// 主方法初始化并显示窗口
public static void main(String[] args)
{
Calculator calc = new Calculator();
calc.setSize(230, 280);
calc.setVisible(true);
}
}
2. 用JAVA编写一个简单的计算器,要求如下:
以下是上图计算器的代码:
packageComputer;
importjava.awt.BorderLayout;
importjava.awt.Color;
importjava.awt.Container;
importjava.awt.Font;
importjava.awt.GridLayout;
importjava.awt.event.ActionEvent;
importjava.awt.event.ActionListener;
importjava.util.Stack;
importjavax.swing.JApplet;
importjavax.swing.JButton;
importjavax.swing.JFrame;
importjavax.swing.JPanel;
importjavax.swing.JTextField;
{
/**
*
*/
=1L;
privateJTextFieldtextField=newJTextField("请输入");
Stringoperator="";//操作
Stringinput="";//输入的式子
booleanflag=true;
//booleanflag1=true;
//booleanflag2=true;
publicvoidinit()//覆写Applet里边的init方法
{
ContainerC=getContentPane();
JButtonb[]=newJButton[16];
JPanelpanel=newJPanel();
C.add(textField,BorderLayout.NORTH);
C.add(panel,BorderLayout.CENTER);
panel.setLayout(newGridLayout(4,4,5,5));
Stringname[]={"7","8","9","+","4","5","6","-","1","2","3","*","0","C","=","/"};//设置按钮
for(inti=0;i<16;i++)//添加按钮
{
b[i]=newJButton(name[i]);
b[i].setBackground(newColor(192,192,192));
b[i].setForeground(Color.BLUE);//数字键设置为蓝颜色
if(i%4==3)
b[i].setForeground(Color.RED);
b[i].setFont(newFont("宋体",Font.PLAIN,16));//设置字体格式
panel.add(b[i]);
b[i].addActionListener(this);
}
b[13].setForeground(Color.RED);//非数字键,即运算键设置为红颜色
b[13].setForeground(Color.RED);
}
publicvoidactionPerformed(ActionEvente)
{
intcnt=0;
StringactionCommand=e.getActionCommand();
if(actionCommand.equals("+")||actionCommand.equals("-")||actionCommand.equals("*")||actionCommand.equals("/"))
input+=""+actionCommand+"";//设置输入,把输入的样式改成需要的样子
elseif(actionCommand.equals("C"))
input="";
elseif(actionCommand.equals("="))//当监听到等号时,则处理input
{
input+="="+compute(input);
textField.setText(input);
input="";
cnt=1;
}
else
input+=actionCommand;//数字为了避免多位数的输入不需要加空格
if(cnt==0)
textField.setText(input);
}
privateStringcompute(Stringinput)//即1237的样例
{
Stringstr[];
str=input.split("");
Stack<Double>s=newStack<Double>();
doublem=Double.parseDouble(str[0]);
s.push(m);
for(inti=1;i<str.length;i++)
{
if(i%2==1)
{
if(str[i].compareTo("+")==0)
{
doublehelp=Double.parseDouble(str[i+1]);
s.push(help);
}
if(str[i].compareTo("-")==0)
{
doublehelp=Double.parseDouble(str[i+1]);
s.push(-help);
}
if(str[i].compareTo("*")==0)
{
doublehelp=Double.parseDouble(str[i+1]);
doubleans=s.peek();//取出栈顶元素
s.pop();//消栈
ans*=help;
s.push(ans);
}
if(str[i].compareTo("/")==0)
{
doublehelp=Double.parseDouble(str[i+1]);
doubleans=s.peek();
s.pop();
ans/=help;
s.push(ans);
}
}
}
doubleans=0d;
while(!s.isEmpty())
{
ans+=s.peek();
s.pop();
}
Stringresult=String.valueOf(ans);
returnresult;
}
publicstaticvoidmain(Stringargs[])
{
JFrameframe=newJFrame("Count");
Countapplet=newCount();
frame.getContentPane().add(applet,BorderLayout.CENTER);
applet.init();//applet的init方法
applet.start();//线程开始
frame.setSize(350,400);//设置窗口大小
frame.setVisible(true);//设置窗口可见
}
}
3. 用JAVA编写一个计算器
打开IED:打开自己java编程的软件,采用的是eclipse软件。
建立java工程。
编写类。
4. java编一个计算器的代码
用Applet还是用Application?
我以前老师好像也布置过一个计算器是Applet的
import java.applet.Applet;
import java.awt.Button;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
//import com.sun.org.apache.xerces.internal.impl.xpath.regex.ParseException;
public class calculator extends Applet implements ActionListener {
/**
*
*/
//private static final long serialVersionUID = 3114597813287650283L;
/* (non-Javadoc)
* @see java.applet.Applet#init()
*/
public int operator = 1; //运算符判断:1-加,2-减,3-乘,4-除;
public double accumulator=0; //运算的累加器;
public double digit = 0;
public boolean bool = true;
public boolean boolca = false;
public String text="0.0";
/*窗体控件*/
public JTextField tf_AccepteData = new JTextField();
public Button bt_Digit;
public Button bt_dot = new Button(".");
public Button bt_add = new Button("+");
public Button bt_plus = new Button("-");
public Button bt_mul = new Button("*");
public Button bt_div = new Button("/");
public Button bt_equal = new Button("=");
public Button bt_clear = new Button("C");
public Button bt_inverse = new Button("1/x");
public Button bt_non = new Button("+/-");
public Button bt_sqrt = new Button("sqrt");
public double scan()
{
text = tf_AccepteData.getText();
try{
digit = Double.parseDouble(text);
}catch(Exception msg){
msg.printStackTrace();
}
return digit;
}
public void accumulate()
{
if(!tf_AccepteData.getText().equals("")){
switch(operator){
case 1:
accumulator += digit;
tf_AccepteData.setText("" + accumulator);
break;
case 2:
accumulator -= digit;
tf_AccepteData.setText("" + accumulator);
break;
case 3:
accumulator *= digit;
tf_AccepteData.setText("" + accumulator);
break;
case 4:
if(digit == 0){
tf_AccepteData.setText("除数不能为零");
operator = 1;
accumulator = 0;
bool = true;
digit = 0;
text="";
}else{
accumulator /=digit;
tf_AccepteData.setText("" + accumulator);
}
break;
default:
break;
}
operator = 1;
}
}
public void init() {
/*初始化窗体*/
setLayout(null);
setSize(225,200);
setBackground(Color.orange);
add(tf_AccepteData);
tf_AccepteData.setHorizontalAlignment(SwingConstants.RIGHT);
tf_AccepteData.setSize(200, 25);
tf_AccepteData.setLocation(10, 10);
tf_AccepteData.setEnabled(false);
tf_AccepteData.setText("0.0");
text = tf_AccepteData.getText();
for(int i= 0; i<=9; i++){
bt_Digit = new Button("" + i);
add(bt_Digit);
bt_Digit.setSize(30, 30);
if(i>=7&&i<=9)
bt_Digit.setLocation((15+40*(i-7)), 50);
if(i>=4&&i<=6)
bt_Digit.setLocation((15+40*(i-4)), 85);
if(i>=1&&i<=3)
bt_Digit.setLocation((15+40*(i-1)), 120);
if(i==0)
bt_Digit.setLocation(15, 155);
bt_Digit.addActionListener(this);
}
/*
* 小数点
*/
add(bt_dot);
bt_dot.setSize(30, 30);
bt_dot.setLocation(95, 155);
bt_dot.addActionListener(this/*new ActionListener()*/);/*{
public void actionPerformed(ActionEvent e) {
}
});*/
/*
* 加法运算
*/
add(bt_add);
bt_add.setSize(30, 30);
bt_add.setLocation(135, 155);
bt_add.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e) {
accumulate();
operator = 1;
bool =true;
boolca = true;
digit = 0;
}
});
/*
* 减法运算
*/
add(bt_plus);
bt_plus.setSize(30, 30);
bt_plus.setLocation(135, 120);
bt_plus.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
accumulate();
operator = 2;
bool =true;
boolca = true;
digit = 0;
}
});
/*
* 乘法运算
*/
add(bt_mul);
bt_mul.setSize(30, 30);
bt_mul.setLocation(135, 85);
bt_mul.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
accumulate();
operator = 3;
bool =true;
boolca = true;
digit = 1;
}
});
/*
* 除法运算
*/
add(bt_div);
bt_div.setSize(30, 30);
bt_div.setLocation(135, 50);
bt_div.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
accumulate();
operator = 4;
bool =true;
boolca = true;
digit = 1;
}
});
/*
* 倒数
*/
add(bt_inverse);
bt_inverse.setSize(30, 30);
bt_inverse.setLocation(175, 120);
bt_inverse.addActionListener(new ActionListener(){
double data=0;
public void actionPerformed(ActionEvent e) {
data = scan();
if(digit==0){
tf_AccepteData.setText("取倒分母不能为零!");
operator = 1;
accumulator = 0;
bool = true;
digit = 0;
text="";
}else{
tf_AccepteData.setText("" + 1.0/data);
}
if(!boolca)
operator = 1;
}
});
/*
* 数学平方根
*/
add(bt_sqrt);
bt_sqrt.setSize(30, 30);
bt_sqrt.setLocation(175, 85);
bt_sqrt.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
scan();
if(digit<0){
tf_AccepteData.setText("函数输入无效!");
operator = 1;
accumulator = 0;
bool = true;
digit = 0;
text="";
}else{
digit = Math.sqrt(digit);
tf_AccepteData.setText("" + digit);
}
if(!boolca)
operator = 1;
}
});
/*
* 取反
*/
add(bt_non);
bt_non.setSize(30, 30);
bt_non.setLocation(55, 155);
bt_non.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e) {
try{
digit = -Double.parseDouble(tf_AccepteData.getText());
tf_AccepteData.setText("" + digit);
}catch(Exception msg){
msg.printStackTrace();
}
if(!boolca)
operator = 1;
}
});
/*
* 等于
*/
add(bt_equal);
bt_equal.setSize(30, 30);
bt_equal.setLocation(175, 155);
bt_equal.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e) {
accumulate();
operator = 1;
bool =true;
digit = 0;
}
});
/*
* 清零运算
*/
add(bt_clear);
bt_clear.setSize(30, 30);
bt_clear.setLocation(175, 50);
bt_clear.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e) {
operator = 1;
accumulator = 0;
bool = true;
digit = 0;
text="";
tf_AccepteData.setText("0.0");
}
});
}
public void actionPerformed(ActionEvent e){
if(bool){
tf_AccepteData.setText("");
bool = false;
}
text = tf_AccepteData.getText();
if((text+e.getActionCommand()).indexOf(".")!=(text+e.getActionCommand()).lastIndexOf(".")) return;
text += e.getActionCommand();
if(text.equals("."))
text = "0"+text;
tf_AccepteData.setText(text);
scan();
}
}
还要写一个CalculatorTest.html网页文件代码如下,写好双击运行CalculatorTest.html就可以了
<!-------------------------CalculatorTest.html ------------------------>
<HTML>
<HEAD>
<TITLE>
小应用程序——一个简单的计算器模型
</TITLE>
</HEAD>
<BODY bgcolor = blue text = yellow >
<center>
<marquee behavior=alternate width = 300 height = 40><br>实现加、减、乘、除四种基本运算</marquee>
<br><br><br>
<APPLET ALIGN = middle CODE = "calculator.class" WIDTH = 225 HEIGHT = 200></APPLET>
<br><br><br>
<input type = button value = " 退出 " onClick="javascript:window.close()">
</center>
<BR>
</BODY>
</HTML>
5. 用Java语言做一个计算器
package 计算器;
import java.awt.*;
import java.awt.event.*;
public class computer implements WindowListener,ActionListener{
private Frame f;
double d0,d1,d2,result;
boolean flag=true;
String s,oper;
TextField tf1;
Panel p=new Panel();
public static void main(String args[])
{ computer e=new computer();
e.go();
}
public void go(){
int i;
result=0;
s=new String();
oper=new String("+");
f=new Frame("计算器");
MenuBar mb=new MenuBar();
f.setMenuBar(mb);
Menu m1=new Menu("编辑");
Menu m2=new Menu("帮助");
Menu m3=new Menu("关于");
mb.add(m1);
mb.add(m3);
mb.setHelpMenu(m2);
tf1=new TextField("",15);
Button[] b=new Button[21];
for(i=1;i<21;i++)
{
b[i]=new Button();
b[i].setFont(new Font("仿宋",0,16));
}
b[1].setLabel("退格");
b[2].setLabel("CE");
b[3].setLabel("C");
b[4].setLabel("/");
b[5].setLabel("7");
b[6].setLabel("8");
b[7].setLabel("9");
b[8].setLabel("*");
b[9].setLabel("4");
b[10].setLabel("5");
b[11].setLabel("6");
b[12].setLabel("-");
b[13].setLabel("1");
b[14].setLabel("2");
b[15].setLabel("3");
b[16].setLabel("+");
b[17].setLabel("0");
b[18].setLabel("+/-");
b[19].setLabel(".");
b[20].setLabel("=");
p.setLayout(new GridLayout(5,4));
p.setBackground(new Color(80,30,100));
for(i=1;i<21;i++)
{ p.add(b[i]);
b[i].addActionListener(this);
b[i].setBackground(new Color(20,130,180));
b[i].setForeground(Color.yellow);
}
for(i=1;i<4;i++)
{
b[i].setBackground(new Color(120,180,170));
b[i].setForeground(Color.blue);
}
for(i=1;i<=4;i++)
{ b[i*4].setBackground(new Color(120,180,170));
b[i*4].setForeground(Color.red);
}
b[20].setBackground(Color.red);
f.addWindowListener(this);
f.setLayout(new BorderLayout());
f.add("North",tf1);
f.add("Center",p);
f.setSize(200,200);
f.setVisible(true);
}
public void windowClosing(WindowEvent e){System.exit(1);}
public void windowOpened(WindowEvent e){}
public void windowIconified(WindowEvent e){}
public void windowDeiconified(WindowEvent e){}
public void windowClosed(WindowEvent e){}
public void windowActivated(WindowEvent e){}
public void windowDeactivated(WindowEvent e){}
public void actionPerformed(ActionEvent e){
String i1=tf1.getText();
s=e.getActionCommand();
if(s=="0"| s=="1"|s=="2"|s=="3"|s=="4"|s=="5"|s=="6"|s=="7"|s=="8"|s=="9"|s==".")
{ if(flag) tf1.setText(i1+s);
else
{ tf1.setText(s);
flag=true;
}
}
else if(s=="+"|s=="-"|s=="*"|s=="/")
{ result=Double.parseDouble(i1);
flag=false;
oper=s;
}
else if(s=="=")
{ d0=Double.parseDouble(i1);
if(oper=="+") result+=d0;
if(oper=="-") result-=d0;
if(oper=="*") result*=d0;
if(oper=="/") result/=d0;
tf1.setText(Double.toString(result));
flag=false;
}
else if(s=="CE")
{ tf1.setText("");
flag=false;
}
else if(s=="C")
{ result=0;
tf1.setText("");
flag=false;
}
else if(s=="退格")
{ String ss=tf1.getText();
int i=ss.length();
ss=ss.substring(0,i-1);
tf1.setText(ss);
}
else if(s=="+/-")
{ d2=-1*Double.parseDouble(tf1.getText());
tf1.setText(Double.toString(d2));
}
}
}
6. 如何用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.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
/**
* 一个计算器,与Windows附件自带计算器的标准版功能、界面相仿。 但还不支持键盘操作。
*/
public class JCalculator extends JFrame implements ActionListener {
/** 计算器上的键的显示名字 */
private final String[] KEYS = { "7", "8", "9", "/", "sqrt", "4", "5", "6",
"*", "%", "1", "2", "3", "-", "1/x", "0", "+/-", ".", "+", "=" };
/** 计算器上的功能键的显示名字 */
private final String[] COMMAND = { "Backspace", "CE", "C" };