當前位置:首頁 » 編程語言 » 用java寫一個計算器

用java寫一個計算器

發布時間: 2023-04-01 13:28:52

A. 用java設計一個簡單的計算器。

無聊寫了個,修復了下Bug:

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);
}

}

熱點內容
qq群里上傳的文件怎麼刪除 發布:2024-04-24 22:13:21 瀏覽:356
途岳配置升級了什麼 發布:2024-04-24 21:55:55 瀏覽:886
刷機安卓10狀態欄圓角如何修復 發布:2024-04-24 21:24:00 瀏覽:135
創建sql資料庫的命令是什麼 發布:2024-04-24 21:23:58 瀏覽:43
不是安卓該如何下載畫質怪獸 發布:2024-04-24 21:18:51 瀏覽:701
php載入網頁 發布:2024-04-24 21:15:20 瀏覽:161
遠程伺服器更換ip地址 發布:2024-04-24 21:14:43 瀏覽:528
什麼時候上線華為方舟編譯器軟體 發布:2024-04-24 21:10:21 瀏覽:631
安卓布局文件指的是哪個 發布:2024-04-24 21:08:05 瀏覽:889
磁帶存儲價格 發布:2024-04-24 21:04:22 瀏覽:902