導航:首頁 > 編程語言 > java編寫一個計算器

java編寫一個計算器

發布時間:2023-09-13 00:52:28

1. 用java程序設計語言設計一個計算器

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編寫一個簡單的計算器,要求如下:

以下是上圖計算器的代碼:

3. 用JAVA編寫一個計算器

  1. 打開IED:打開自己java編程的軟體,採用的是eclipse軟體。

  2. 建立java工程。

  3. 編寫類。

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

閱讀全文

與java編寫一個計算器相關的資料

熱點內容
劉駿微信 瀏覽:113
書旗舊版本80 瀏覽:467
教編程考什麼證 瀏覽:990
下載編程貓後哪裡有客服 瀏覽:13
如何編輯歌曲文件格式 瀏覽:638
cf無限領取cdk工具 瀏覽:350
如何讓手機文件保存到電腦上 瀏覽:459
sa資料庫默認密碼是多少 瀏覽:191
電腦正在查找文件 瀏覽:541
一個文件盒省內寄順豐多少錢 瀏覽:41
誅仙62坐騎怎麼升級到63 瀏覽:926
linux以日期查看日誌記錄 瀏覽:446
工業大數據是什麼東西 瀏覽:881
魅族note3怎麼重置網路 瀏覽:510
c語言程序設計模 瀏覽:92
兒童怎麼做可編程機 瀏覽:603
數據計算屬於什麼統計學 瀏覽:921
07word怎麼去掉標記 瀏覽:979
qq緩存的數據是什麼 瀏覽:348
LED主Kv文件多少兆 瀏覽:856

友情鏈接