導航:首頁 > 編程語言 > java計算器計算代碼

java計算器計算代碼

發布時間:2023-03-04 11:42:16

java 編寫計算器 要代碼最簡單的

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Font;
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;

public class CalculatorB implements ActionListener {
private JFrame frame;

private JTextField field;

private JButton[] allButtons;

private JButton clearButton;

// 構造初始化 成員變數
public CalculatorB() {
frame = new JFrame("Calculator v1.1");
field = new JTextField(25);
allButtons = new JButton[16];
String str = "123+456-789*0.=/";
for (int i = 0; i < 16; i++) {
allButtons[i] = new JButton(str.substring(i, i + 1));
}
clearButton = new JButton("CLEAR");
// 調用界面的初始化方法
init();
// 調用設置文本框的字體和顏色 方法
setFontAndColor();
addEventHandler();
}

public void addEventHandler() {
for (int i = 0; i < allButtons.length; i++) {
allButtons[i].addActionListener(this);
clearButton.addActionListener(this);
}
}

private String op = null;

private String m = null;

private String n = null;

private boolean cls = false;

private void setResult() {
if (field.getText().equals("")) {
cls = true;
m = null;
n = null;
} else if (m != null) {
n = field.getText();
if (op.equals("+")) {
field.setText(Double.parseDouble(m) + Double.parseDouble(n)
+ "");
} else if (op.equals("-")) {
field.setText(Double.parseDouble(m) - Double.parseDouble(n)
+ "");
} else if (op.equals("*")) {
field.setText(Double.parseDouble(m) * Double.parseDouble(n)
+ "");
} else if (op.equals("/")) {
field.setText(Double.parseDouble(m) / Double.parseDouble(n)
+ "");
}
cls = true;
m = null;
n = null;
}

}

public void actionPerformed(ActionEvent e) {
String str = e.getActionCommand();// 得到被點的按鈕名稱
if ("0123456789.".indexOf(str) != -1) {
if (cls) {
field.setText("");
cls = false;
}
field.setText(field.getText() + str);
} else if ("+-*/".indexOf(str) != -1) {
if (field.getText().equals("")) {
op = str;
} else if (m == null) {
m = field.getText();
op = str;
field.setText("");
} else if (m != null) {
setResult();
m = field.getText();
op = str;
}

} else if (str.equals("=")) {
setResult();
} else if (str.equals("CLEAR")) {
field.setText("");
m = null;
n = null;
}
}

public void init() {
frame.setLayout(new BorderLayout());
JPanel northPannel = new JPanel();
JPanel centerPannel = new JPanel();
JPanel southPannel = new JPanel();
northPannel.setLayout(new FlowLayout());
centerPannel.setLayout(new GridLayout(4, 4));
southPannel.setLayout(new FlowLayout());
northPannel.add(field);
southPannel.add(clearButton);
for (int i = 0; i < allButtons.length; i++) {
centerPannel.add(allButtons[i]);
}
frame.add(northPannel, BorderLayout.NORTH);
frame.add(southPannel, BorderLayout.SOUTH);
frame.add(centerPannel, BorderLayout.CENTER);

}

public void setFontAndColor() {
field.setFont(new Font("宋體", Font.BOLD, 20));
field.setForeground(Color.PINK);
field.setBackground(new Color(0x2a, 0x3b, 0x4f));
}

public void showMe() {
frame.pack(); // 系統調整大小---很重要
// frame.setSize(600, 400);// 自定義窗體大小
frame.setLocation(500, 400);// 設置窗體的啟動位置
frame.setResizable(false);
frame.setVisible(true);
frame.setDefaultCloseOperation(3);
}

public static void main(String[] args) {
new CalculatorB().showMe();
}

}

以上代碼是我的原創回答,可以直接運行的代碼。並且此計算器可以實現連續計算,樓主試試去,有什麼意見和建議再提

② 用JAVA編寫的科學計算器源代碼

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
class Counter extends WindowAdapter
{
static JFrame f=new JFrame("計算器");
static JTextField text1=new JTextField("0.");
static String source="";
static String cal="";
static String object="";
static boolean flag=false;
static boolean flag1=true;
static boolean flag2=false;
public void init()
{
try
{
Container c=f.getContentPane();
JPanel pan1=new JPanel();
JButton b1=new JButton("1");
JButton b2=new JButton("2");
JButton b3=new JButton("3");
JButton b4=new JButton("4");
JButton b5=new JButton("5");
JButton b6=new JButton("6");
JButton b7=new JButton("7");
JButton b8=new JButton("8");
JButton b9=new JButton("9");
JButton b0=new JButton("0");
JButton b11=new JButton("+");
JButton b12=new JButton("-");
JButton b13=new JButton("*");
JButton b14=new JButton("/");
JButton b15=new JButton(".");
JButton b16=new JButton("=");
JButton bclar=new JButton("清零");
text1.setHorizontalAlignment(JTextField.RIGHT);
c.add(text1,"North");
c.add(pan1);
A aa=new A();
Result re=new Result();
Opertion op=new Opertion();
Clar cl=new Clar();
b1.addActionListener(aa);
b2.addActionListener(aa);
b3.addActionListener(aa);
b4.addActionListener(aa);
b5.addActionListener(aa);
b6.addActionListener(aa);
b7.addActionListener(aa);
b8.addActionListener(aa);
b9.addActionListener(aa);
b0.addActionListener(aa);
b11.addActionListener(op);
b12.addActionListener(op);
b13.addActionListener(op);
b14.addActionListener(op);
b16.addActionListener(re);
b15.addActionListener(aa);
bclar.addActionListener(cl);
pan1.add(b1);
pan1.add(b2);
pan1.add(b3);
pan1.add(b11);
pan1.add(b4);
pan1.add(b5);
pan1.add(b6);
pan1.add(b12);
pan1.add(b7);
pan1.add(b8);
pan1.add(b9);
pan1.add(b13);
pan1.add(b0);
pan1.add(b15);
pan1.add(b16);
pan1.add(b14);
pan1.add(bclar);
f.setSize(200,220);
f.setVisible(true);
}
catch(Exception e)
{
System.out.println(e.getMessage());
}

}
class A implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String a=text1.getText();
String s=e.getActionCommand();
if(a.equals("0.")||a.equals("+")||a.equals("-")||a.equals("*")||a.equals("/"))
text1.setText(s);
else {
if(flag2)
{
text1.setText(s);
flag2=false;
}
else
text1.setText(a+s);

}
}
}
class Opertion implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
cal=e.getActionCommand();
if(flag1==true)
source=text1.getText();
text1.setText(cal);
flag1=false;
flag=true;
}
}
class Result implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
double num1;
num1=Double.parseDouble(source);
object=text1.getText();
double num2;
num2=Double.parseDouble(object);
double result=0;
if(cal.equals("+"))
result=num1+num2;
if(cal.equals("-"))
result=num1-num2;
if(cal.equals("*"))
result=num1*num2;
if(cal.equals("/"))
if(num2==0)
text1.setText("除數不能為0");
else
result=num1/num2;
String s1=Double.toString(result);
text1.setText(s1);
flag1=true;
flag2=true;
}
}
class Clar implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
text1.setText("0.");
}
}

public static void main(String[] args)
{
Counter count=new Counter();
count.init();
}

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

③ 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>

④ JAVA簡單咋做,計算器代碼

簡單寫了下,代碼如下請參照:

/**
*計算器類
*
*@authorAdministrator
*
*/
{

=3868243398506940702L;

//文本框
privateJTextFieldresult;
//按鈕數組
privateJButton[]buttons;
//按鈕文本
privatefinalString[]characters={"7","8","9","/","4","5","6",
"*","1","2","3","-","0",".","=","+"};
//是否為第一個輸入的數字
privatebooleanisFirstDigit=true;
//運算結果
privatedoubleresultNum=0.0;
//運算符
privateStringoperator="=";

publicCalculator(Stringtitle){
//設置標題欄
super(title);
//初始化各組件
init();
//注冊各組件監聽器
registerListener();

//顯示窗體
setVisible(true);
}

/**
*初始化各組件
*/
privatevoidinit(){
//常用屬性初始化
setSize(220,200);
setResizable(false);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);

/*文本框對象初始化*/
result=newJTextField("0");
//文本右對齊
result.setHorizontalAlignment(JTextField.RIGHT);
//設置是否可編輯
result.setEditable(false);
/*按鈕初始化*/
buttons=newJButton[characters.length];
for(inti=0;i<buttons.length;i++){
buttons[i]=newJButton(characters[i]);
buttons[i].setFocusable(false);//不允許按鈕定位焦點
}
/*將文本框與按鈕添加到窗體中*/
add(result,BorderLayout.NORTH);
JPanelpnl=newJPanel(newGridLayout(4,4,5,5));
for(JButtonjButton:buttons){
pnl.add(jButton);
}
add(pnl);

this.getContentPane().setFocusable(true);
}

/**
*注冊監聽器
*/
privatevoidregisterListener(){
for(JButtonjButton:buttons){
jButton.addActionListener(this);
}

//注冊鍵盤事件
this.getContentPane().addKeyListener(newKeyAdapter(){
@Override
publicvoidkeyPressed(KeyEvente){
Stringtext=String.valueOf(e.getKeyChar());
if(Character.isDigit(text.charAt(0))||".".equals(text)){//數字或小數點
handleNumber(text);
}elseif("+-*/=".indexOf(text)!=-1){//運算符
handleOperator(text);
}elseif(e.getKeyCode()==8){//退格鍵
Stringtmp=result.getText().trim();
if(tmp.length()==1){
result.setText("0");
isFirstDigit=true;
}else{
result.setText(tmp.substring(0,tmp.length()-1));
}
}
}
});
}

@Override
publicvoidactionPerformed(ActionEvente){
JButtonbtn=(JButton)e.getSource();
Stringtext=btn.getText().trim();

if(Character.isDigit(text.charAt(0))||".".equals(text)){//處理數字和小數點
handleNumber(text);
}else{//處理運算符
handleOperator(text);
}
}

/**
*處理數字和小數點
*
*@paramtext
*/
privatevoidhandleNumber(Stringtext){
if(isFirstDigit){//第一次輸入
if(".".equals(text)){
this.result.setText("0.");
}else{
this.result.setText(text);
}
}elseif("0".equals(text)&&"0".equals(this.result.getText())){
isFirstDigit=true;
return;
}elseif(".".equals(text)&&this.result.getText().indexOf(".")==-1){
this.result.setText(this.result.getText()+".");
}elseif(!".".equals(text)){
this.result.setText(this.result.getText()+text);
}

isFirstDigit=false;
}

/**
*處理運算符
*
*@paramtext
*/
privatevoidhandleOperator(Stringtext){
switch(operator){//處理各項運算適用於JDK1.7版本
case"+":
resultNum+=Double.parseDouble(this.result.getText());
break;
case"-":
resultNum-=Double.parseDouble(this.result.getText());
break;
case"*":
resultNum*=Double.parseDouble(this.result.getText());
break;
case"/":
resultNum/=Double.parseDouble(this.result.getText());
break;
case"=":
resultNum=Double.parseDouble(this.result.getText());
break;
}
//將文本框的值修改為運算結果
this.result.setText(String.valueOf(resultNum));
//將點擊的運算符放入operator保存
operator=text;
//下一個數字第一次點擊
isFirstDigit=true;
}

publicstaticvoidmain(String[]args){
newCalculator("MyCalculator");
}
}

運行結果如下:

閱讀全文

與java計算器計算代碼相關的資料

熱點內容
怎麼改合同網站 瀏覽:73
網路鬥地主記牌器怎麼實現的 瀏覽:377
ps鏡像文件製作教程 瀏覽:45
系統分頁文件大小設置多少 瀏覽:447
win10有線無法上網 瀏覽:339
wps無法訪問指定文件 瀏覽:96
iphone4震動壞了 瀏覽:217
安卓隨機數軟體rand 瀏覽:356
CNC編程如何掌握公差 瀏覽:297
linux搭建php環境 瀏覽:514
星形網路怎麼表示有故障 瀏覽:719
dbf文件c語言處理excel 瀏覽:138
金蝶kis支持win10嗎 瀏覽:113
常州採集物聯網大數據平台有哪些 瀏覽:950
win10休眠文件改到d盤 瀏覽:626
如何編程手機app軟體 瀏覽:656
node獲取文件名 瀏覽:367
iphoneios7怎麼設置鈴聲 瀏覽:52
手機qq激活星鑽 瀏覽:302
html中引入js文件路徑 瀏覽:83

友情鏈接