用java写一个计算器
A. 用java设计一个简单的计算器。
无聊写了个,修复了下Bug:
 importjava.awt.event.ActionEvent;
importjava.awt.event.ActionEvent;
importjava.awt.event.ActionListener;
importjavax.swing.JButton;
importjavax.swing.JFrame;
importjavax.swing.JLabel;
importjavax.swing.JOptionPane;
importjavax.swing.JTextField;
{
=1L;
privateJButtonplus,rece,multiply,divice,reset;
privateJTextFieldone,two,result;
privatebooleandevice_falg=false;
privatefinalintwidth=400,height=300;
publicCalculate(){
super("修改密码");
this.setLayout(null);
this.setSize(width,height);
init();
Layout();
}
publicvoidinit(){
plus=newJButton("加");
rece=newJButton("减");
multiply=newJButton("乘");
divice=newJButton("除");
reset=newJButton("清空");
one=newJTextField();
two=newJTextField();
result=newJTextField();
}
publicvoidLayout(){
this.add(newJLabel("第一个数")).setBounds(20,10,60,80);
this.add(one).setBounds(100,38,100,25);
this.add(newJLabel("第二个数")).setBounds(20,40,60,80);
this.add(two).setBounds(100,70,100,25);
this.add(newJLabel("结果")).setBounds(20,85,60,80);
this.add(result).setBounds(100,110,100,25);
this.add(plus).setBounds(70,170,80,25);
this.add(rece).setBounds(200,170,80,25);
this.add(multiply).setBounds(70,200,80,25);
this.add(divice).setBounds(200,200,80,25);
this.add(reset).setBounds(300,220,80,25);
plus.addActionListener(this);
rece.addActionListener(this);
multiply.addActionListener(this);
divice.addActionListener(this);
reset.addActionListener(this);
this.setVisible(true);
this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
}
publicbooleanFormat(){
booleanFLAG=false;
booleanflag=false;
Stringone=this.one.getText().toString().trim();
Stringtwo=this.two.getText().toString().trim();
if(one==null||one.equals("")||two==null||two.equals("")){
JOptionPane.showMessageDialog(getParent(),"请输入完整信息!");
FLAG=false;
flag=true;
}
booleanboll_1=one.matches("[\d]{1,100}");
booleanboll_2=two.matches("[\d]{1,100}");
booleanboll_3=one.matches("[\d]{1,100}+[.]+[\d]{1,100}");
booleanboll_4=two.matches("[\d]{1,100}+[.]+[\d]{1,100}");
if(flag){
returnfalse;
}
if((boll_1&&boll_2)||(boll_3&&boll_4)||(boll_1&&boll_4)
||(boll_3&&boll_2)){
FLAG=true;
}else{
JOptionPane.showMessageDialog(getParent(),"请输入数字!");
FLAG=false;
}
if(FLAG&&device_falg){
if(Double.parseDouble(two)==0){
JOptionPane.showMessageDialog(getParent(),"被除数不能为0!");
FLAG=false;
device_falg=false;
}
}
returnFLAG;
}
publicdoublePlus(doubleone,doubletwo){
returnone+two;
}
publicdoubleMultiply(doubleone,doubletwo){
returnone*two;
}
publicdoubleDivice(doubleone,doubletwo){
returnone/two;
}
publicdoubleRece(doubleone,doubletwo){
returnone-two;
}
publicvoidClear(){
one.setText("");
two.setText("");
result.setText("");
}
@Override
publicvoidactionPerformed(ActionEvente){
Objecto=e.getSource();
if(o==reset){
Clear();
return;
}
if(o==divice){
device_falg=true;
}
if(!Format()){
return;
}
doubleone=Double.parseDouble(this.one.getText());
doubletwo=Double.parseDouble(this.two.getText());
doubleresult=0;
if(o==plus){
result=Plus(one,two);
}elseif(o==rece){
result=Rece(one,two);
}elseif(o==multiply){
result=Multiply(one,two);
}elseif(o==divice){
result=Divice(one,two);
}
this.result.setText(""+result);
}
publicstaticvoidmain(String[]args){
newCalculate();
}
}
B. 用JAVA编写的计算器
package main;
import java.awt.Button;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.math.BigDecimal;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class Calculator extends JFrame implements ActionListener {
	static Panel pan = new Panel();
	static JTextField textField = new JTextField("0");
	static Button b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, bp, ba, bs, bm, bd,
			be, bc, bt, bf, bh;
	private StringBuffer temp = new StringBuffer("");
	private String optValue = "0";
	private String optType="";
	private boolean isChoiseOptType=true;
	public void init() {
		b0 = new Button("0");
		b0.addActionListener(this);
		b1 = new Button("1");
		b1.addActionListener(this);
		b2 = new Button("2");
		b2.addActionListener(this);
		b3 = new Button("3");
		b3.addActionListener(this);
		b4 = new Button("4");
		b4.addActionListener(this);
		b5 = new Button("5");
		b5.addActionListener(this);
		b6 = new Button("6");
		b6.addActionListener(this);
		b7 = new Button("7");
		b7.addActionListener(this);
		b8 = new Button("8");
		b8.addActionListener(this);
		b9 = new Button("9");
		b9.addActionListener(this);
		bp = new Button(".");
		bp.addActionListener(this);
		ba = new Button("+");
		ba.addActionListener(this);
		bs = new Button("-");
		bs.addActionListener(this);
		bm = new Button("*");
		bm.addActionListener(this);
		bd = new Button("/");
		bd.addActionListener(this);
		be = new Button("=");
		be.addActionListener(this);
		bc = new Button("c");
		bc.addActionListener(this);
		bt = new Button("退格");
		bt.addActionListener(this);
		bf = new Button("1/x");
		bf.addActionListener(this);
		bh = new Button("+/-");
		bh.addActionListener(this);
		this.setTitle("计算机");
		this.setLayout(null);
		this.setSize(260, 300);
		this.setResizable(false);
		GridLayout grid = new GridLayout(4, 5);
		pan.setLayout(grid);
		pan.setBounds(20, 60, 150, 120);
		textField.setBounds(20, 35, 150, 20);
		textField.setBackground(Color.cyan);
		textField.setHorizontalAlignment(textField.RIGHT);
		textField.setEditable(false);
		pan.add(b1);
		pan.add(b2);
		pan.add(b3);
		pan.add(ba);
		pan.add(bc);
		pan.add(b4);
		pan.add(b5);
		pan.add(b6);
		pan.add(bs);
		pan.add(bt);
		pan.add(b7);
		pan.add(b8);
		pan.add(b9);
		pan.add(bm);
		pan.add(bf);
		pan.add(b0);
		pan.add(bh);
		pan.add(bp);
		pan.add(bd);
		pan.add(be);
		this.add(textField);
		this.add(pan);
	}
	public static void main(String[] args) {
		Calculator frm = new Calculator();
		frm.init();
		frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frm.setVisible(true);
	}
	@SuppressWarnings("static-access")
	@Override
	public void actionPerformed(ActionEvent e) {
		String value="0";
		if (e.getSource().equals(b0)) {
			this.temp.append(b0.getLabel());
			this.textField.setText(this.temp.toString());
			isChoiseOptType=false;
		} else if (e.getSource().equals(b1)) {
			this.temp.append(b1.getLabel());
			this.textField.setText(this.temp.toString());
			isChoiseOptType=false;
		} else if (e.getSource().equals(b2)) {
			this.temp.append(b2.getLabel());
			this.textField.setText(this.temp.toString());
			isChoiseOptType=false;
		} else if (e.getSource().equals(b3)) {
			this.temp.append(b3.getLabel());
			this.textField.setText(this.temp.toString());
			isChoiseOptType=false;
		} else if (e.getSource().equals(b4)) {
			this.temp.append(b4.getLabel());
			this.textField.setText(this.temp.toString());
			isChoiseOptType=false;
		} else if (e.getSource().equals(b5)) {
			this.temp.append(b5.getLabel());
			this.textField.setText(this.temp.toString());
			isChoiseOptType=false;
		} else if (e.getSource().equals(b6)) {
			this.temp.append(b6.getLabel());
			this.textField.setText(this.temp.toString());
			isChoiseOptType=false;
		} else if (e.getSource().equals(b7)) {
			this.temp.append(b7.getLabel());
			this.textField.setText(this.temp.toString());
			isChoiseOptType=false;
		} else if (e.getSource().equals(b8)) {
			this.temp.append(b8.getLabel());
			this.textField.setText(this.temp.toString());
			isChoiseOptType=false;
		} else if (e.getSource().equals(b9)) {
			this.temp.append(b9.getLabel());
			this.textField.setText(this.temp.toString());
			isChoiseOptType=false;
		} else if (e.getSource().equals(bp)) {
			if(this.temp.length()<=0)
				this.temp.append("0");
			this.temp.append(bp.getLabel());
			this.textField.setText(this.temp.toString());
			isChoiseOptType=false;
		} else if (e.getSource().equals(ba)) {
			if(!isChoiseOptType){
			    value=this.textField.getText();
					if(value.lastIndexOf(".")==value.length()-1){
						value=value.substring(0,value.length()-1);
					}
				this.optValue=value;
				this.temp=new StringBuffer("");
			}
			this.optType=ba.getLabel();
			isChoiseOptType=true;
		} else if (e.getSource().equals(bs)) {
			if(!isChoiseOptType){
			 value=this.textField.getText();
			 if(value.lastIndexOf(".")==value.length()-1){
					value=value.substring(0,value.length()-1);
			 }
			 this.optValue=value;
			 this.temp=new StringBuffer("");
			}
			 this.optType=bs.getLabel();
			 isChoiseOptType=true;
		} else if (e.getSource().equals(bm)) {
			if(!isChoiseOptType){
				 value=this.textField.getText();
				 if(value.lastIndexOf(".")==value.length()-1){
						value=value.substring(0,value.length()-1);
				 }
				 this.optValue=value;
				 this.temp=new StringBuffer("");
			}
			 this.optType=bm.getLabel();
			 isChoiseOptType=true;
		} else if (e.getSource().equals(bd)) {
			if(!isChoiseOptType){
			 value=this.textField.getText();
			 if(value.lastIndexOf(".")==value.length()-1){
					value=value.substring(0,value.length()-1);
			 }
			 this.optValue=value;
			 this.temp=new StringBuffer("");
			}
			 this.optType=bd.getLabel();
			 isChoiseOptType=true;
		}else if (e.getSource().equals(be)) {
		if(!this.optType.equals("")){
			BigDecimal opt1=new BigDecimal(this.optValue);
			value=this.textField.getText();
			 if(value.lastIndexOf(".")==value.length()-1){
					value=value.substring(0,value.length()-1);
			 }
			BigDecimal opt2=new BigDecimal(value);
			BigDecimal result=new BigDecimal(0);
			if(this.optType.equals("+")){
				result=opt1.add(opt2);
			}else if(this.optType.equals("-")){
				result=opt1.subtract(opt2);
			}else if(this.optType.equals("*")){
				result=opt1.multiply(opt2);
			}else if(this.optType.equals("/")){
				result=opt1.divide(opt2);
			}else if(this.optType.equals("%")){
				result=opt1.remainder(opt2);
			}
			this.textField.setText(result.toString());
			this.temp=new StringBuffer("");
			isChoiseOptType=false;
			this.optValue="0";
		}
		} else if (e.getSource().equals(bc)) {
			this.temp=new StringBuffer();
			this.textField.setText("0");
		} else if (e.getSource().equals(bt)) {
		    value=this.textField.getText();
		    value=value.substring(0,value.length()-1);
		    if(value.indexOf("-")>=0 && value.length()<=1){
		    	value="0";
		    	this.temp=new StringBuffer("");
		    }else{
		    	this.temp=new StringBuffer(value);
		    }
		    this.textField.setText(value);
		}else if (e.getSource().equals(bh)) {
			value=this.textField.getText();
			if(value.indexOf("-")==0){
				value=value.substring(1,value.length());
			}else{
				value="-"+value;
			}
			this.temp=new StringBuffer(value);
			this.textField.setText(value);
		} else if (e.getSource().equals(bf)) {
			this.optValue=this.textField.getText();
			 if(value.lastIndexOf(".")==value.length()-1){
				 this.optValue=this.optValue.substring(0,this.optValue.length()-1);
			 }
			Integer opt1=new Integer(this.optValue);
			if(!opt1.toString().equals("0")){
				this.textField.setText(1.0/opt1.intValue()+"");
				System.out.println(1/opt1.intValue()+"");
			}else{
				this.textField.setText("0");
			}
			this.temp=new StringBuffer("");
			this.optType="";
			this.optValue="0";
			
		}
	}
}
C. 用java编写一个简单计算器
/*
* @(#)JCalculator.java 1.00 06/17/2015
*/
importjava.awt.*;
importjava.awt.event.*;
importjavax.swing.*;
/**
* A simple calculator program.
*<p>I saw this program in a QQ group, and help a friend correct it.</p>
*
*@authorSingyuenYip
*@version1.00 12/29/2009
*@seeJFrame
*@seeActionListener
*/
{
/**
* Serial Version UID
*/
= -169068472193786457L;
/**
* This class help close the Window.
*@authorSingyuenYip
*
*/
{
publicvoidwindowClosing(WindowEvent we) {
System.exit(0);
}
}
inti;
// Strings for Digit & Operator buttons.
privatefinalString[]str= {"7","8","9","/","4","5","6","*","1",
"2","3","-",".","0","=","+"};
// Build buttons.
JButton[]buttons=newJButton[str.length];
// For cancel or reset.
JButtonreset=newJButton("CE");
// Build the text field to show the result.
JTextFielddisplay=newJTextField("0");
/**
* Constructor without parameters.
*/
publicJCalculator() {
super("Calculator");
// Add a panel.
JPanel panel1 =newJPanel(newGridLayout(4, 4));
// panel1.setLayout(new GridLayout(4,4));
for(i= 0;i<str.length;i++) {
buttons[i] =newJButton(str[i]);
panel1.add(buttons[i]);
}
JPanel panel2 =newJPanel(newBorderLayout());
// panel2.setLayout(new BorderLayout());
panel2.add("Center",display);
panel2.add("East",reset);
// JPanel panel3 = new Panel();
getContentPane().setLayout(newBorderLayout());
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(newWindowCloser());
// 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();
}
publicvoidactionPerformed(ActionEvent e) {
Object target = e.getSource();
String label = e.getActionCommand();
if(target ==reset)
handleReset();
elseif("0123456789.".indexOf(label) > 0)
handleNumber(label);
else
handleOperator(label);
}
// Is the first digit pressed?
booleanisFirstDigit=true;
/**
* Number handling.
*@paramkey the key of the button.
*/
publicvoidhandleNumber(String key) {
if(isFirstDigit)
display.setText(key);
elseif((key.equals(".")) && (display.getText().indexOf(".") < 0))
display.setText(display.getText() +".");
elseif(!key.equals("."))
display.setText(display.getText() + key);
isFirstDigit=false;
}
/**
* Reset the calculator.
*/
publicvoidhandleReset() {
display.setText("0");
isFirstDigit=true;
operator="=";
}
doublenumber= 0.0;
Stringoperator="=";
/**
* Handling the operation.
*@paramkey pressed operator's key.
*/
publicvoidhandleOperator(String key) {
if(operator.equals("+"))
number+= Double.valueOf(display.getText());
elseif(operator.equals("-"))
number-= Double.valueOf(display.getText());
elseif(operator.equals("*"))
number*= Double.valueOf(display.getText());
elseif(operator.equals("/"))
number/= Double.valueOf(display.getText());
elseif(operator.equals("="))
number= Double.valueOf(display.getText());
display.setText(String.valueOf(number));
operator= key;
isFirstDigit=true;
}
publicstaticvoidmain(String[] args) {
newJCalculator();
}
}
运行界面:

D. 怎么用java设计一个计算器
建议直接网上找源码,有做好的那种
E. 用Java编写一个简单的计算器程序
import java.awt.*; 
import java.awt.event.*; 
public class CalcAppDemo extends Frame{ 
private TextField t_result; 
private Panel p_main; //主面板 
private Panel p_num; //数字面板 
private Panel p_oper; //操作符面板 
private Panel p_show; //显示面板 
private Button b_num[]; //数字按钮 
private Button b_oper[]; //操作符面板 
public CalcAppDemo(String title){ 
setTitle(title); 
t_result = new TextField("0.0", 21); 
p_main = new Panel(); 
p_num = new Panel(); 
p_oper = new Panel(); 
p_show = new Panel(); 
p_main.setLayout(new BorderLayout()); 
p_num.setLayout(new GridLayout(4, 3, 1, 1)); 
p_oper.setLayout(new GridLayout(4, 2, 1, 1)); 
b_num = new Button[12]; 
for(int i=0; i<9; i++) 
{ 
b_num[i] = new Button(new Integer(i+1).toString()); 
} 
b_num[9] = new Button("0"); 
b_num[10] = new Button("cls"); 
b_num[11] = new Button("."); 
for(int i=0; i<12; i++) 
{ 
p_num.add(b_num[i]); 
} 
b_oper = new Button[8]; 
b_oper[0] = new Button("+"); 
b_oper[1] = new Button("-"); 
b_oper[2] = new Button("*"); 
b_oper[3] = new Button("/"); 
b_oper[4] = new Button("pow"); 
b_oper[5] = new Button("sqrt"); 
b_oper[6] = new Button("+/-"); 
b_oper[7] = new Button("="); 
for(int i=0; i<8; i++) // 
{ 
p_oper.add(b_oper[i]); 
} 
t_result.setEditable(false); 
p_show.add(t_result, BorderLayout.NORTH); 
p_main.add(p_show, BorderLayout.NORTH); 
p_main.add(p_num, BorderLayout.WEST); 
p_main.add(p_oper, BorderLayout.EAST); 
this.add(p_main, BorderLayout.CENTER); 
setSize(400, 400); 
setResizable(false); 
pack(); 
this.addWindowListener(new WindowAdapter(){ 
public void windowClosing(WindowEvent e) 
{ 
System.exit(0); 
} 
}); 
ButtonListener b1 = new ButtonListener(); 
for(int i=0; i<12; i++) 
{ 
b_num[i].addActionListener(b1); 
} 
for(int i=0; i<8; i++) 
{ 
b_oper[i].addActionListener(b1); 
} 
} 
class ButtonListener implements ActionListener 
{ 
private String lastOp; //存储上一此操作符 
private String strVal; //存储数字对应的字符串 
private double total; //总数 
private double number; //存储新输入的数 
private boolean firsttime; //判断是否第一次按下的是操作符按钮 
private boolean operatorPressed;//判断是否已经按过操作符按钮 
ButtonListener() 
{ 
firsttime = true; 
strVal = ""; 
} 
//事件处理器 
public void actionPerformed(ActionEvent e) 
{ 
String s = ((Button)e.getSource()).getLabel().trim(); 
if(Character.isDigit(s.charAt(0))) 
{//判断是操作数还是操作符 
handleNumber(s); 
} 
else 
{ 
calculate(s); 
} 
} 
//判断是一元操作符还是二元操作符,并根据操作符类型做计算 
void calculate(String op) 
{ 
operatorPressed = true; 
if(firsttime&&! isUnary(op)) 
{ 
total = getNumberOnDisplay(); 
firsttime = false; 
} 
if(isUnary(op)) 
{ 
handleUnaryOp(op); 
} 
else if(lastOp != null) 
{ 
handleBinaryOp(lastOp); 
} 
if(! isUnary(op)) 
{ 
lastOp = op; 
} 
} 
//判断是否一元操作符 
boolean isUnary(String s) 
{ 
return s.equals("=") 
||s.equals("cls")||s.equals("sqrt") 
||s.equals("+/-")||s.equals("."); 
} 
//处理一元操作符 
void handleUnaryOp(String op) 
{ 
if(op.equals("+/-")) 
{// 
number = negate(getNumberOnDisplay() + ""); 
t_result.setText(""); 
t_result.setText(number + ""); 
return; 
}else if(op.equals(".")) 
{ 
handleDecPoint(); 
return; 
}else if(op.equals("sqrt")) 
{ 
number = Math.sqrt(getNumberOnDisplay()); 
t_result.setText(""); 
t_result.setText(number + ""); 
return; 
}else if(op.equals("=")) 
{// 
if(lastOp!= null && !isUnary(lastOp)) 
{ 
handleBinaryOp(lastOp); 
} 
lastOp = null; 
firsttime = true; 
return; 
}else 
{ 
clear(); 
} 
} 
//处理二元运算符 
void handleBinaryOp(String op) 
{ 
if(op.equals("+")) 
{ 
total +=number; 
}else if(op.equals("-")) 
{ 
total -=number; 
}else if(op.equals("*")) 
{ 
total *=number; 
}else if(op.equals("/")) 
{ 
try 
{ 
total /=number; 
}catch(ArithmeticException ae){} 
}else if(op.equals("pow")) 
total = Math.pow(total, number); 
//t_result.setText(""); 
lastOp = null; 
// strVal = ""; 
number = 0; 
t_result.setText(total + ""); 
} 
//该方法用于处理数字按钮 
void handleNumber(String s) 
{ 
if(!operatorPressed) 
{ 
strVal += s; 
}else 
{ 
operatorPressed = false; 
strVal = s; 
} 
// 
number = new Double(strVal).doubleValue(); 
t_result.setText(""); 
t_result.setText(strVal); 
} 
//该方法用于按下"."按钮 
void handleDecPoint() 
{ 
operatorPressed = false; 
// 
if(strVal.indexOf(".")<0) 
{ 
strVal += "."; 
} 
t_result.setText(""); 
t_result.setText(strVal); 
} 
//该方法用于将一个数求反 
double negate(String s) 
{ 
operatorPressed = false; 
//如果是一个整数,去掉小数点后面的0 
if(number == (int)number) 
{ 
s = s.substring(0,s.indexOf(".")); 
} 
//如果无"-"增加在该数的前面 
if(s.indexOf("-")<0) 
{ 
strVal = "-" + s; 
} 
else 
{ 
strVal = s.substring(1); 
} 
return new Double(strVal).doubleValue(); 
} 
//将显示框中的值转换成Double 
double getNumberOnDisplay() 
{ 
return new Double(t_result.getText()).doubleValue(); 
} 
//清除屏幕并设置所有的标识 
void clear() 
{ 
firsttime = true; 
lastOp = null; 
strVal = ""; 
total = 0; 
number = 0; 
t_result.setText("0"); 
} 
} 
public static void main(String[] args) { 
CalcAppDemo c = new CalcAppDemo("简单的计算器程序"); 
c.setVisible(true); 
} 
}
