public class MyComputer implements ActionListener{
成都創(chuàng)新互聯(lián)是一家集網(wǎng)站建設(shè),新干企業(yè)網(wǎng)站建設(shè),新干品牌網(wǎng)站建設(shè),網(wǎng)站定制,新干網(wǎng)站建設(shè)報(bào)價(jià),網(wǎng)絡(luò)營(yíng)銷(xiāo),網(wǎng)絡(luò)優(yōu)化,新干網(wǎng)站推廣為一體的創(chuàng)新建站企業(yè),幫助傳統(tǒng)企業(yè)提升企業(yè)形象加強(qiáng)企業(yè)競(jìng)爭(zhēng)力??沙浞譂M(mǎn)足這一群體相比中小企業(yè)更為豐富、高端、多元的互聯(lián)網(wǎng)需求。同時(shí)我們時(shí)刻保持專(zhuān)業(yè)、時(shí)尚、前沿,時(shí)刻以成就客戶(hù)成長(zhǎng)自我,堅(jiān)持不斷學(xué)習(xí)、思考、沉淀、凈化自己,讓我們?yōu)楦嗟钠髽I(yè)打造出實(shí)用型網(wǎng)站。
private boolean appendnumber = false;
private boolean append = false;
private boolean flag = false;
private String temp1 = null;
private String op1 = null;
private JTextField jtf = new JTextField("0.",28);
public MyComputer(){
init();
}
private void init() {
/*
* 下面都是在畫(huà)計(jì)算機(jī)界面你想看也可以,
* 不看也行,具體計(jì)算在public void
* actionPerformed(ActionEvent e)
* 里
*/
JFrame frame = new JFrame("我的計(jì)算器");
JPanel panelTop = new JPanel();
panelTop.setLayout(new FlowLayout());
panelTop.add(jtf);
JPanel panelBotton = new JPanel();
String[] str = {"BackSpace","CE","C","+",
"7","8","9","-",
"4","5","6","*",
"1","2","3","/",
"0","+/-",".","="};
JButton[] jb = new JButton[str.length];
panelBotton.setLayout(new GridLayout(5,4));
for(int i = 0;i jb.length;i++)
{
jb[i] = new JButton(str[i]);
panelBotton.add(jb[i]);
jb[i].addActionListener(this);
}
frame.add(panelTop,BorderLayout.NORTH);
frame.add(panelBotton);
frame.setSize(400, 400);
frame.setVisible(true);
}
public static void main(String[] args) {
new MyComputer();
}
public void actionPerformed(ActionEvent e) {
String comm = e.getActionCommand();//獲得button里的數(shù)據(jù)
/*
* "0123456789".indexOf(comm)!=-1是判斷button里獲得的數(shù)據(jù)
* 是0---9的情況
*/
if ("0123456789".indexOf(comm)!=-1) {
if(!appendnumber){
jtf.setText(comm);
appendnumber = true;
}else{
jtf.setText(jtf.getText()+comm);
}
}
/*
* 判斷button里獲得的數(shù)據(jù)是加減乘除的情況
*/
if("+-*/".indexOf(comm)!=-1){
//在遇到加減乘除的符號(hào)時(shí)我們先存儲(chǔ)剛輸入的值
temp1 = jtf.getText();
//然后存儲(chǔ)符號(hào)
op1 = comm;
/*
* 然后可以重新輸入數(shù)據(jù)到輸入框,所以這時(shí)候我們
* 不能追加數(shù)據(jù),設(shè)置追加數(shù)據(jù)標(biāo)志為false
*/
appendnumber = false;
}
/*
* 判斷button里獲得的數(shù)據(jù)是等號(hào)的情況
*/
else if("=".equals(comm)) {
if(temp1==null||"".equals(temp1))return;
/*
* 遇到等號(hào)的時(shí)候,我們?nèi)〕鰟偛疟4娴臄?shù)據(jù)和當(dāng)前輸入的數(shù)據(jù)做運(yùn)算
*/
double num1 = Double.parseDouble(temp1);//轉(zhuǎn)化數(shù)據(jù)成double型的
double num2 = Double.parseDouble(jtf.getText());//轉(zhuǎn)化數(shù)據(jù)成double型的
//取出剛才保存的符號(hào)看是加減乘除的那種運(yùn)算
if("+".equals(op1)){
num1+=num2;
}
if("-".equals(op1)){
num1-=num2;
}
if ("*".equals(op1)) {
num1*=num2;
}
if("/".equals(op1)){
num1/=num2;
}
jtf.setText(num1+"");
appendnumber = false;
}
/*
* 判斷button里獲得的數(shù)據(jù)是小數(shù)點(diǎn)的情況
*/
else if (".".equals(comm)) {
if(jtf.getText().indexOf(".")==-1){
append = true;
}
if (append) {
jtf.setText(jtf.getText()+".");
append = false;
appendnumber = true;
}
}
/*
* 判斷button里獲得的數(shù)據(jù)是在數(shù)據(jù)前面加正負(fù)號(hào)的情況
*/
else if ("+/-".equals(comm)) {
if(!flag){
jtf.setText("-"+jtf.getText());
flag = true;
}
else{
String result = jtf.getText().substring(1, jtf.getText().length());
jtf.setText(result);
flag = false;
}
}
/*
* 判斷button里獲得的數(shù)據(jù)是清除輸入框的情況
*/
else if ("C".equals(comm)) {
jtf.setText("0.");
appendnumber = false;
}
/*
* 判斷button里獲得的數(shù)據(jù)是清除輸入框的情況
*/
else if ("CE".equals(comm)) {
jtf.setText("0.");
appendnumber = false;
}
/*
* 判斷button里獲得的數(shù)據(jù)是輸入框的數(shù)據(jù)退一位的情況
*/
else if ("BackSpace".equals(comm)) {
if(jtf.getText()==null||"".equals(jtf.getText()))return;
String result = jtf.getText().substring(0, jtf.getText().length()-1);
jtf.setText(result+"");
appendnumber = true;
}
}
}
很簡(jiǎn)單的東西?。∧銈?nèi)シ帜敲炊嗲闆r??!這個(gè)東西啊一個(gè)人寫(xiě)半個(gè)小時(shí)就OK了,如果你會(huì)寫(xiě)的話,其實(shí)初學(xué)者們別因?yàn)閯e人怎么怎么說(shuō)就嚇倒,其實(shí)這寫(xiě)起來(lái)都沒(méi)多少代碼的,都是些小東西而已。最重要的是你要搞懂來(lái)龍去脈就不難了,別聽(tīng)一些人吹誰(shuí)誰(shuí)牛X這類(lèi)的,其實(shí)你認(rèn)真的去做,認(rèn)真的去思考,你也不比他們差。
我有一個(gè)計(jì)算器程序,有代碼:
package book.gui;
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;
/**
* 一個(gè)計(jì)算器,與Windows附件自帶計(jì)算器的標(biāo)準(zhǔn)版功能、界面相仿。
* 但還不支持鍵盤(pán)操作。
*/
public class Calculator extends JFrame implements ActionListener {
/** 計(jì)算器上的鍵的顯示名字 */
private final String[] KEYS = { "7", "8", "9", "/", "sqrt", "4", "5", "6",
"*", "%", "1", "2", "3", "-", "1/x", "0", "+/-", ".", "+", "=" };
/** 計(jì)算器上的功能鍵的顯示名字 */
private final String[] COMMAND = { "Backspace", "CE", "C" };
/** 計(jì)算器左邊的M的顯示名字 */
private final String[] M = { " ", "MC", "MR", "MS", "M+" };
/** 計(jì)算器上鍵的按鈕 */
private JButton keys[] = new JButton[KEYS.length];
/** 計(jì)算器上的功能鍵的按鈕 */
private JButton commands[] = new JButton[COMMAND.length];
/** 計(jì)算器左邊的M的按鈕 */
private JButton m[] = new JButton[M.length];
/** 計(jì)算結(jié)果文本框 */
private JTextField resultText = new JTextField("0");
// 標(biāo)志用戶(hù)按的是否是整個(gè)表達(dá)式的第一個(gè)數(shù)字,或者是運(yùn)算符后的第一個(gè)數(shù)字
private boolean firstDigit = true;
// 計(jì)算的中間結(jié)果。
private double resultNum = 0.0;
// 當(dāng)前運(yùn)算的運(yùn)算符
private String operator = "=";
// 操作是否合法
private boolean operateValidFlag = true;
/**
* 構(gòu)造函數(shù)
*/
public Calculator(){
super();
//初始化計(jì)算器
init();
//設(shè)置計(jì)算器的背景顏色
this.setBackground(Color.LIGHT_GRAY);
this.setTitle("計(jì)算器");
//在屏幕(500, 300)坐標(biāo)處顯示計(jì)算器
this.setLocation(500, 300);
//不許修改計(jì)算器的大小
this.setResizable(false);
//使計(jì)算器中各組件大小合適
this.pack();
}
/**
* 初始化計(jì)算器
*/
private void init() {
// 文本框中的內(nèi)容采用右對(duì)齊方式
resultText.setHorizontalAlignment(JTextField.RIGHT);
// 不允許修改結(jié)果文本框
resultText.setEditable(false);
// 設(shè)置文本框背景顏色為白色
resultText.setBackground(Color.white);
//初始化計(jì)算器上鍵的按鈕,將鍵放在一個(gè)畫(huà)板內(nèi)
JPanel calckeysPanel = new JPanel();
//用網(wǎng)格布局器,4行,5列的網(wǎng)格,網(wǎng)格之間的水平方向間隔為3個(gè)象素,垂直方向間隔為3個(gè)象素
calckeysPanel.setLayout(new GridLayout(4, 5, 3, 3));
for (int i = 0; i KEYS.length; i++) {
keys[i] = new JButton(KEYS[i]);
calckeysPanel.add(keys[i]);
keys[i].setForeground(Color.blue);
}
//運(yùn)算符鍵用紅色標(biāo)示,其他鍵用藍(lán)色表示
keys[3].setForeground(Color.red);
keys[8].setForeground(Color.red);
keys[13].setForeground(Color.red);
keys[18].setForeground(Color.red);
keys[19].setForeground(Color.red);
//初始化功能鍵,都用紅色標(biāo)示。將功能鍵放在一個(gè)畫(huà)板內(nèi)
JPanel commandsPanel = new JPanel();
//用網(wǎng)格布局器,1行,3列的網(wǎng)格,網(wǎng)格之間的水平方向間隔為3個(gè)象素,垂直方向間隔為3個(gè)象素
commandsPanel.setLayout(new GridLayout(1, 3, 3, 3));
for (int i = 0; i COMMAND.length; i++) {
commands[i] = new JButton(COMMAND[i]);
commandsPanel.add(commands[i]);
commands[i].setForeground(Color.red);
}
//初始化M鍵,用紅色標(biāo)示,將M鍵放在一個(gè)畫(huà)板內(nèi)
JPanel calmsPanel = new JPanel();
//用網(wǎng)格布局管理器,5行,1列的網(wǎng)格,網(wǎng)格之間的水平方向間隔為3個(gè)象素,垂直方向間隔為3個(gè)象素
calmsPanel.setLayout(new GridLayout(5, 1, 3, 3));
for (int i = 0; i M.length; i++) {
m[i] = new JButton(M[i]);
calmsPanel.add(m[i]);
m[i].setForeground(Color.red);
}
//下面進(jìn)行計(jì)算器的整體布局,將calckeys和command畫(huà)板放在計(jì)算器的中部,
//將文本框放在北部,將calms畫(huà)板放在計(jì)算器的西部。
//新建一個(gè)大的畫(huà)板,將上面建立的command和calckeys畫(huà)板放在該畫(huà)板內(nèi)
JPanel panel1 = new JPanel();
//畫(huà)板采用邊界布局管理器,畫(huà)板里組件之間的水平和垂直方向上間隔都為3象素
panel1.setLayout(new BorderLayout(3, 3));
panel1.add("North", commandsPanel);
panel1.add("West", calckeysPanel);
//建立一個(gè)畫(huà)板放文本框
JPanel top = new JPanel();
top.setLayout(new BorderLayout());
top.add("Center", resultText);
//整體布局
getContentPane().setLayout(new BorderLayout(3, 5));
getContentPane().add("North", top);
getContentPane().add("Center", panel1);
getContentPane().add("West", calmsPanel);
//為各按鈕添加事件偵聽(tīng)器
//都使用同一個(gè)事件偵聽(tīng)器,即本對(duì)象。本類(lèi)的聲明中有implements ActionListener
for (int i = 0; i KEYS.length; i++) {
keys[i].addActionListener(this);
}
for (int i = 0; i COMMAND.length; i++) {
commands[i].addActionListener(this);
}
for (int i = 0; i M.length; i++) {
m[i].addActionListener(this);
}
}
/**
* 處理事件
*/
public void actionPerformed(ActionEvent e) {
//獲取事件源的標(biāo)簽
String label = e.getActionCommand();
if (label.equals(COMMAND[0])){
//用戶(hù)按了"Backspace"鍵
handleBackspace();
} else if (label.equals(COMMAND[1])) {
//用戶(hù)按了"CE"鍵
resultText.setText("0");
} else if (label.equals(COMMAND[2])){
//用戶(hù)按了"C"鍵
handleC();
} else if ("0123456789.".indexOf(label) = 0) {
//用戶(hù)按了數(shù)字鍵或者小數(shù)點(diǎn)鍵
handleNumber(label);
// handlezero(zero);
} else {
//用戶(hù)按了運(yùn)算符鍵
handleOperator(label);
}
}
/**
* 處理Backspace鍵被按下的事件
*/
private void handleBackspace() {
String text = resultText.getText();
int i = text.length();
if (i 0) {
//退格,將文本最后一個(gè)字符去掉
text = text.substring(0, i - 1);
if (text.length() == 0) {
//如果文本沒(méi)有了內(nèi)容,則初始化計(jì)算器的各種值
resultText.setText("0");
firstDigit = true;
operator = "=";
} else {
//顯示新的文本
resultText.setText(text);
}
}
}
/**
* 處理數(shù)字鍵被按下的事件
* @param key
*/
private void handleNumber(String key) {
if (firstDigit) {
//輸入的第一個(gè)數(shù)字
resultText.setText(key);
} else if ((key.equals(".")) (resultText.getText().indexOf(".") 0)){
//輸入的是小數(shù)點(diǎn),并且之前沒(méi)有小數(shù)點(diǎn),則將小數(shù)點(diǎn)附在結(jié)果文本框的后面
resultText.setText(resultText.getText() + ".");
} else if (!key.equals(".")) {
//如果輸入的不是小數(shù)點(diǎn),則將數(shù)字附在結(jié)果文本框的后面
resultText.setText(resultText.getText() + key);
}
//以后輸入的肯定不是第一個(gè)數(shù)字了
firstDigit = false;
}
/**
* 處理C鍵被按下的事件
*/
private void handleC() {
//初始化計(jì)算器的各種值
resultText.setText("0");
firstDigit = true;
operator = "=";
}
/**
* 處理運(yùn)算符鍵被按下的事件
* @param key
*/
private void handleOperator(String key) {
if (operator.equals("/")) {
//除法運(yùn)算
//如果當(dāng)前結(jié)果文本框中的值等于0
if (getNumberFromText() == 0.0){
//操作不合法
operateValidFlag = false;
resultText.setText("除數(shù)不能為零");
} else {
resultNum /= getNumberFromText();
}
} else if (operator.equals("1/x")) {
//倒數(shù)運(yùn)算
if (resultNum == 0.0){
//操作不合法
operateValidFlag = false;
resultText.setText("零沒(méi)有倒數(shù)");
} else {
resultNum = 1 / resultNum;
}
} else if (operator.equals("+")){
//加法運(yùn)算
resultNum += getNumberFromText();
} else if (operator.equals("-")){
//減法運(yùn)算
resultNum -= getNumberFromText();
} else if (operator.equals("*")){
//乘法運(yùn)算
resultNum *= getNumberFromText();
} else if (operator.equals("sqrt")) {
//平方根運(yùn)算
resultNum = Math.sqrt(resultNum);
} else if (operator.equals("%")){
//百分號(hào)運(yùn)算,除以100
resultNum = resultNum / 100;
} else if (operator.equals("+/-")){
//正數(shù)負(fù)數(shù)運(yùn)算
resultNum = resultNum * (-1);
} else if (operator.equals("=")){
//賦值運(yùn)算
resultNum = getNumberFromText();
}
if (operateValidFlag) {
//雙精度浮點(diǎn)數(shù)的運(yùn)算
long t1;
double t2;
t1 = (long) resultNum;
t2 = resultNum - t1;
if (t2 == 0) {
resultText.setText(String.valueOf(t1));
} else {
resultText.setText(String.valueOf(resultNum));
}
}
//運(yùn)算符等于用戶(hù)按的按鈕
operator = key;
firstDigit = true;
operateValidFlag = true;
}
/**
* 從結(jié)果文本框中獲取數(shù)字
* @return
*/
private double getNumberFromText() {
double result = 0;
try {
result = Double.valueOf(resultText.getText()).doubleValue();
} catch (NumberFormatException e){
}
return result;
}
public static void main(String args[]) {
Calculator calculator1 = new Calculator();
calculator1.setVisible(true);
calculator1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
//引入各種類(lèi)文件
import?java.awt.Button;
import?java.awt.Color;
import?java.awt.FlowLayout;
import?java.awt.Font;
import?java.awt.Frame;
import?java.awt.GridLayout;
import?java.awt.Panel;
import?java.awt.TextField;
import?java.awt.event.ActionEvent;
import?java.awt.event.ActionListener;
//定義JsqFrame繼承Frame
class?JsqFrame?extends?Frame?{
double?d1,?d2;??//定義兩個(gè)double類(lèi)型的變量
int?op?=?-1;??//定義兩個(gè)int類(lèi)型的變量
static?TextField?tf;//定義靜態(tài)對(duì)象TextField
CalPanelL?p1;??//定義CalPanelL對(duì)象
//?Constructor構(gòu)造方法
JsqFrame()?{
//以下設(shè)置屬性
super("計(jì)算器");
setLayout(new?FlowLayout());
setResizable(false);
setSize(250,?250);
tf?=?new?TextField(18);
tf.setEditable(false);
tf.setBackground(Color.lightGray);
tf.setForeground(Color.red);
tf.setFont(new?Font("Arial",?Font.BOLD,?16));
add(tf);
p1?=?new?CalPanelL();
add(p1);
setVisible(true);
//?addWindowListener(new?Wclose());
}
//添加按鈕繼承Button類(lèi)
class?CalButton?extends?Button?{
CalButton(String?s)?{
//設(shè)置按鈕屬性
super(s);
setBackground(Color.WHITE);?//設(shè)置顏色為白色
}
}
//定義顯示器繼承Panel類(lèi)
class?CalPanelL?extends?Panel?{
CalButton?a,?c,?b0,?b1,?b2,?b3,?b4,?b5,?b6,?b7,?b8,?b9,?bPN,?bPoint,
bAdd,?bSub,?bMul,?bDiv,?bL,?bR,?bLn,?bEqual,?bCE,?bQuit;
CalPanelL()?{
//設(shè)置顯示器的屬性
setLayout(new?GridLayout(6,?4));
setFont(new?Font("TimesRoman",?Font.BOLD,?16));
a?=?new?CalButton("");
c?=?new?CalButton("");
b0?=?new?CalButton("0");
b1?=?new?CalButton("1");
b2?=?new?CalButton("2");
b3?=?new?CalButton("3");
b4?=?new?CalButton("4");
b5?=?new?CalButton("5");
b6?=?new?CalButton("6");
b7?=?new?CalButton("7");
b8?=?new?CalButton("8");
b9?=?new?CalButton("9");
bPN?=?new?CalButton("+/-");
bPoint?=?new?CalButton(".");
//?設(shè)置按鈕
bAdd?=?new?CalButton("+");
bSub?=?new?CalButton("-");
bMul?=?new?CalButton("*");
bDiv?=?new?CalButton("/");
bL?=?new?CalButton("(");
bR?=?new?CalButton(")");
bLn?=?new?CalButton("ln");
bEqual?=?new?CalButton("=");
bCE?=?new?CalButton("CE");
bQuit?=?new?CalButton("退出");
//?加入按鈕
add(a);
add(c);
add(bCE);
bCE.addActionListener(new?PressBCE());
add(bQuit);
bQuit.addActionListener(new?PressBQuit());
add(b7);
b7.addActionListener(new?PressB7());
add(b8);
b8.addActionListener(new?PressB8());
add(b9);
b9.addActionListener(new?PressB9());
add(bDiv);
bDiv.addActionListener(new?PressBDiv());
add(b4);
b4.addActionListener(new?PressB4());
add(b5);
b5.addActionListener(new?PressB5());
add(b6);
b6.addActionListener(new?PressB6());
add(bMul);
bMul.addActionListener(new?PressBMul());
add(b1);
b1.addActionListener(new?PressB1());
add(b2);
b2.addActionListener(new?PressB2());
add(b3);
b3.addActionListener(new?PressB3());
add(bSub);
bSub.addActionListener(new?PressBSub());
add(b0);
b0.addActionListener(new?PressB0());
add(bPoint);
bPoint.addActionListener(new?PressBPoint());
add(bPN);
bPN.addActionListener(new?PressBPN());
;
add(bAdd);
bAdd.addActionListener(new?PressBAdd());
add(bL);
bL.addActionListener(new?PressBL());
add(bR);
bR.addActionListener(new?PressBR());
add(bLn);
bLn.addActionListener(new?PressBLn());
add(bEqual);
bEqual.addActionListener(new?PressBEqual());
}
}
//定義PressBAdd實(shí)現(xiàn)ActionListener
//大體的意思是按計(jì)算機(jī)按鍵的時(shí)出發(fā)的時(shí)間,設(shè)置按鍵的監(jiān)聽(tīng)[加號(hào)的監(jiān)聽(tīng)事件]
class?PressBAdd?implements?ActionListener?{
public?void?actionPerformed(ActionEvent?e)?{
try?{
String?d1?=?tf.getText();
op?=?0;
tf.setText(d1?+?"+");
}?catch?(Exception?ee)?{
}
}
}
//定義PressBSub實(shí)現(xiàn)ActionListener
//大體的意思是按計(jì)算機(jī)按鍵的時(shí)出發(fā)的時(shí)間,設(shè)置按鍵的監(jiān)聽(tīng)[減號(hào)的監(jiān)聽(tīng)事件]
class?PressBSub?implements?ActionListener?{
public?void?actionPerformed(ActionEvent?e)?{
try?{
String?d1?=?tf.getText();
op?=?1;
tf.setText(d1?+?"-");
}?catch?(Exception?ee)?{
}
}
}
//定義PressBMul實(shí)現(xiàn)ActionListener
//大體的意思是按計(jì)算機(jī)按鍵的時(shí)出發(fā)的時(shí)間,設(shè)置按鍵的監(jiān)聽(tīng)[乘號(hào)的監(jiān)聽(tīng)事件]
class?PressBMul?implements?ActionListener?{
public?void?actionPerformed(ActionEvent?e)?{
try?{
String?d1?=?tf.getText();
op?=?2;
tf.setText(d1?+?"*");
}?catch?(Exception?ee)?{
}
}
}
//定義PressBDiv實(shí)現(xiàn)ActionListener
//大體的意思是按計(jì)算機(jī)按鍵的時(shí)出發(fā)的時(shí)間,設(shè)置按鍵的監(jiān)聽(tīng)[除號(hào)的監(jiān)聽(tīng)事件]
class?PressBDiv?implements?ActionListener?{
public?void?actionPerformed(ActionEvent?e)?{
try?{
String?d1?=?tf.getText();
op?=?3;
tf.setText(d1?+?"/");
}?catch?(Exception?ee)?{
}
}
}
//定義PressBL實(shí)現(xiàn)ActionListener
//大體的意思是按計(jì)算機(jī)按鍵的時(shí)出發(fā)的時(shí)間,設(shè)置按鍵的監(jiān)聽(tīng)[向左鍵的監(jiān)聽(tīng)事件]
class?PressBL?implements?ActionListener?{
public?void?actionPerformed(ActionEvent?e)?{
try?{
String?d1?=?tf.getText();
op?=?3;
tf.setText(d1?+?"(");
}?catch?(Exception?ee)?{
}
}
}
//定義PressBR實(shí)現(xiàn)ActionListener
//大體的意思是按計(jì)算機(jī)按鍵的時(shí)出發(fā)的時(shí)間,設(shè)置按鍵的監(jiān)聽(tīng)[向右鍵的監(jiān)聽(tīng)事件]
class?PressBR?implements?ActionListener?{
public?void?actionPerformed(ActionEvent?e)?{
try?{
String?d1?=?tf.getText();
op?=?3;
tf.setText(d1?+?")");
}?catch?(Exception?ee)?{
}
}
}
//定義PressBEqual實(shí)現(xiàn)ActionListener
//大體的意思是按計(jì)算機(jī)按鍵的時(shí)出發(fā)的時(shí)間,設(shè)置按鍵的監(jiān)聽(tīng)[等號(hào)的監(jiān)聽(tīng)事件]
class?PressBEqual?implements?ActionListener?{
public?void?actionPerformed(ActionEvent?e)?{
try?{
Jsq?jsq?=?new?Jsq();
String?s?=?tf.getText();
System.out.println(s);
while?(s.indexOf("(")?+?1??0??s.indexOf(")")??0)?{
String?s1?=?jsq.caculateHigh(s);
System.out.println(s1);
s?=?s1;
}
String?str?=?jsq.cacluteMain(s);
System.out.println(str);
tf.setText(String.valueOf(str));
}?catch?(Exception?ee)?{
}
}
}
/*
*?批量寫(xiě)吧
*?以下是按1、2、3等等的監(jiān)聽(tīng)事件
*?還有清零的等等監(jiān)聽(tīng)事件
*/
class?PressBLn?implements?ActionListener?{
public?void?actionPerformed(ActionEvent?e)?{
try?{
double?x?=?Double.parseDouble(tf.getText());
double?y;
y?=?Math.log10(x);
tf.setText(y?+?"");
}?catch?(Exception?ee)?{
}
}
}
class?PressBCE?implements?ActionListener?{
public?void?actionPerformed(ActionEvent?e)?{
tf.setText("");
}
}
class?PressBPN?implements?ActionListener?{
public?void?actionPerformed(ActionEvent?e)?{
try?{
String?text?=?tf.getText();
if?(text?!=?"")?{
if?(text.charAt(0)?==?'-')
tf.setText(text.substring(1));
else?if?(text.charAt(0)?=?'0'??text.charAt(0)?=?'9')
tf.setText("-"?+?text.substring(0));
else?if?(text.charAt(0)?==?'.')
tf.setText("-0"?+?text.substring(0));
}
}?catch?(Exception?ee)?{
}
}
}
class?PressBPoint?implements?ActionListener?{
public?void?actionPerformed(ActionEvent?e)?{
String?text?=?tf.getText();
if?(text.lastIndexOf(".")?==?-1)
tf.setText(text?+?".");
}
}
class?PressB0?implements?ActionListener?{
public?void?actionPerformed(ActionEvent?e)?{
String?text?=?tf.getText();
tf.setText(text?+?"0");
}
}
class?PressB1?implements?ActionListener?{
public?void?actionPerformed(ActionEvent?e)?{
String?text?=?tf.getText();
tf.setText(text?+?"1");
}
}
class?PressB2?implements?ActionListener?{
public?void?actionPerformed(ActionEvent?e)?{
String?text?=?tf.getText();
tf.setText(text?+?"2");
}
}
class?PressB3?implements?ActionListener?{
public?void?actionPerformed(ActionEvent?e)?{
String?text?=?tf.getText();
tf.setText(text?+?"3");
}
}
class?PressB4?implements?ActionListener?{
public?void?actionPerformed(ActionEvent?e)?{
String?text?=?tf.getText();
tf.setText(text?+?"4");
}
}
class?PressB5?implements?ActionListener?{
public?void?actionPerformed(ActionEvent?e)?{
String?text?=?tf.getText();
tf.setText(text?+?"5");
}
}
class?PressB6?implements?ActionListener?{
public?void?actionPerformed(ActionEvent?e)?{
String?text?=?tf.getText();
tf.setText(text?+?"6");
}
}
class?PressB7?implements?ActionListener?{
public?void?actionPerformed(ActionEvent?e)?{
String?text?=?tf.getText();
tf.setText(text?+?"7");
}
}
class?PressB8?implements?ActionListener?{
public?void?actionPerformed(ActionEvent?e)?{
String?text?=?tf.getText();
tf.setText(text?+?"8");
}
}
class?PressB9?implements?ActionListener?{
public?void?actionPerformed(ActionEvent?e)?{
String?text?=?tf.getText();
tf.setText(text?+?"9");
}
}
class?PressBQuit?implements?ActionListener?{
public?void?actionPerformed(ActionEvent?e)?{
System.exit(0);
}
}
public?void?Js()?{
String?text?=?tf.getText();
tf.setText(text);
}
}
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
//while(true){
Scanner sc = new Scanner(System.in);
System.out.println(jisuan(sc.next()));
}
private static float jisuan(String cont){
List arryList = new ArrayList();
char[] str = cont.toCharArray();
Character astr;
String s = "";
for(int i=0;istr.length;i++){
astr = str[i];
if(astr=='+'||astr=='-'||astr=='*'||astr=='/'||astr=='=')
{
arryList.add(s);
s="";
if(astr!='='){
arryList.add(astr.toString());
}
}else{
s += astr;
}
}
float count = 0;
List jjlist = chengchuModel(arryList);
String ssf = "";
String var1 = "";
String var2 = "";
if(jjlist.size()=3){
for(int i=1;ijjlist.size();i=i+2){ //jjlist中就只有加減法了
ssf = (String)jjlist.get(i); // 獲得jjlist中的加法或減法字符進(jìn)行判斷
var2 = (String)jjlist.get(i+1);
if(i==1){ //判斷第一個(gè)運(yùn)算符是加號(hào)還是減號(hào),兩個(gè)情況下的運(yùn)行也是不同的
var1 = (String)jjlist.get(i-1); //只有第一次加減的時(shí)候才會(huì)去取前一個(gè)數(shù)字進(jìn)行運(yùn)算
if(ssf.trim().equals("-")){
count = Float.parseFloat(var1) - Float.parseFloat(var2);
}else{
count = Float.parseFloat(var1) + Float.parseFloat(var2);
}
}else{
if(ssf.trim().equals("-")){
count = count - Float.parseFloat(var2);
}else{
count = count + Float.parseFloat(var2);
}
}
}
}else{
count = Float.parseFloat(jjlist.get(0).toString());
}
return count;
}
private static boolean checkstr(String str){
if(!str.trim().equals("*")!str.trim().equals("/"))
return true;
return false;
}
private static boolean cheng(String str){
if(str.trim().equals("*"))
return true;
return false;
}
private static boolean chu(String str){
if(str.trim().equals("/"))
return true;
return false;
}
private static List chengchuModel(List list){ //將輸入的算術(shù)的所有乘除法算出來(lái)只剩下加減法
String var1 ="";
String var2 ="";
String var3 ="";
for(int i=1;ilist.size();i=i+2){
var1 = (String)list.get(i-1);
var2 = (String)list.get(i);
var3 = (String)list.get(i+1);
if(!checkstr(var2)){
if(cheng(var2)){
list.set(i-1, String.valueOf((Float.parseFloat(var1)*Float.parseFloat(var3))));
list.remove(i);
list.remove(i);
i = i-2;
//
}else if(chu(var2)){
list.set(i-1, String.valueOf((Float.parseFloat(var1)/Float.parseFloat(var3))));
list.remove(i);
list.remove(i);
i = i-2;
}
}
}
return list;
}
}
測(cè)試:
輸入:33-6*5+7/4=
結(jié)果:4.75
package CalcTest;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.ScrollPane;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DecimalFormat;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;
import org.w3c.dom.Text;
import com.sun.org.apache.bcel.internal.generic.JsrInstruction;
public class Calc extends JFrame implements ActionListener{
public final int max = 8;//定義文本框最多輸入字符
String copy;
boolean enter;
int key = -1,prekey = -1;
double vard,answerd;
String curDate="";
Double opate1 = 0.0;
Double opate2 = 0.0;
DecimalFormat df;
JPanel ButtonPanel,okPanel;
JButton jb[];
JTextField jtf;
JScrollPane jsp;
JButton jia,jian,cheng,chu,dian,dengyu;
JMenuBar jmb;
JMenu bjM,ckM,bzM;
JTextArea jta;
JMenuItem copyM,pasteM,closeM,helpM,gyM;
JButton b1;
boolean start;
public Calc(){
enter = true;
start =true;
df = new DecimalFormat("0.#########");
Container c = getContentPane();
//**以下為菜單之類(lèi)的
jmb = new JMenuBar();
bjM = new JMenu("編輯(E)");
ckM = new JMenu("查看(V)");
bzM = new JMenu("幫助(H)");
copyM = new JMenuItem("復(fù)制(C)");
pasteM = new JMenuItem("粘貼(V)");
closeM = new JMenuItem("關(guān)閉(E)");
helpM = new JMenuItem("幫助主題");
gyM = new JMenuItem("關(guān)于計(jì)算器");
jmb.add(bjM);
jmb.add(ckM);
jmb.add(bzM);
bjM.add(copyM);
bjM.add(pasteM);
ckM.add(closeM);
bzM.add(helpM);
bzM.add(gyM);
setJMenuBar(jmb);//顯示菜單條
//**以上為菜單類(lèi)的
//**以下注冊(cè)菜單監(jiān)聽(tīng)器
copyM.addActionListener(this);
pasteM.addActionListener(this);
closeM.addActionListener(this);
helpM.addActionListener(this);
gyM.addActionListener(this);
//**以上注冊(cè)菜單監(jiān)聽(tīng)器
jtf = new JTextField(35);
jtf.setText("0.");
jtf.setEditable(false);
//jtf.setComponentOrientation(java.awt.ComponentOrientation.RIGHT_TO_LEFT);//設(shè)置文本框從右往左
jtf.setHorizontalAlignment(JTextField.RIGHT);//跟上面效果一樣
jtf.setText("");//設(shè)置每次都重新獲取
//**以下為按鈕設(shè)置
jb = new JButton[10];
jia = new JButton("+");
jian = new JButton("-");
cheng = new JButton("*");
chu = new JButton("\\");
dian = new JButton(".");
dengyu = new JButton("=");
jia.addActionListener(this);
jian.addActionListener(this);
cheng.addActionListener(this);
chu.addActionListener(this);
dian.addActionListener(this);
dengyu.addActionListener(this);
ButtonPanel = new JPanel();
for(int i=0;ijb.length;i++){
jb[i] = new JButton(Integer.toString(i));//實(shí)現(xiàn)將整形轉(zhuǎn)字符串
jb[i].setForeground(new Color(99,00,00));
jb[i].addActionListener(Calc.this);//為每個(gè)按鈕注冊(cè)監(jiān)聽(tīng)器
}
ButtonPanel.setLayout(new GridLayout(4,4));//設(shè)置格子布局4行4列
ButtonPanel.add(jb[1]);
ButtonPanel.add(jb[2]);
ButtonPanel.add(jb[3]);
ButtonPanel.add(jia);
ButtonPanel.add(jb[4]);
ButtonPanel.add(jb[5]);
ButtonPanel.add(jb[6]);
ButtonPanel.add(jian);
ButtonPanel.add(jb[7]);
ButtonPanel.add(jb[8]);
ButtonPanel.add(jb[9]);
ButtonPanel.add(cheng);
ButtonPanel.add(jb[0]);
ButtonPanel.add(dian);
ButtonPanel.add(dengyu);
ButtonPanel.add(chu);
//**以上為按鈕設(shè)置
//**以下為幫助主題
jta = new JTextArea(5,10);
jsp = new JScrollPane(jta);
jta.setEditable(false);
jta.setFont(new Font("楷體",Font.BOLD,20));
jta.append("執(zhí)行簡(jiǎn)單計(jì)算\n");
jta.append("1. 鍵入計(jì)算的第一個(gè)數(shù)字。\n");
jta.append("2. 單擊“+”執(zhí)行加、“-”執(zhí)行減、“*”執(zhí)行乘或“/”執(zhí)行除。\n");
jta.append("3. 鍵入計(jì)算的下一個(gè)數(shù)字。\n");
jta.append("4. 輸入所有剩余的運(yùn)算符和數(shù)字。\n");
jta.append("5. 單擊“=”。\n");
//**以上為幫助主題
//**以下為清零
okPanel = new JPanel();
b1 = new JButton("C");
okPanel.add(b1);
//**以上為清零
b1.addActionListener(this);//注冊(cè)監(jiān)聽(tīng)器
c.add(jtf,BorderLayout.NORTH);
c.add(ButtonPanel,BorderLayout.CENTER);
c.add(okPanel,BorderLayout.SOUTH);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e) {
Object temp = e.getSource();
if(temp == dian enter == true){
boolean isDot = false;
if(jtf.getText().length()==0)
isDot=true;
for(int i = 0;ijtf.getText().length();i++){
if('.'== jtf.getText().charAt(i)){
System.out.println(i);
isDot = true;
break;
}
}
if(isDot==false)
jtf.setText(jtf.getText() + ".");
}
if(jtf.getText().length()==max){
jtf.setText("輸入超出最大長(zhǎng)度");
enter=false;
}
if((temp == jia || temp == jian || temp == cheng || temp ==chu) enter == true){
if(temp == jia){
switch (prekey) {
case 0:
answerd += Double.parseDouble(jtf.getText());//將String值轉(zhuǎn)換成DOUBLE,返回一個(gè)新的double值
break;
case 1:
answerd -= Double.parseDouble(jtf.getText());
case 2:
answerd *= Double.parseDouble(jtf.getText());
case 3:
if (Double.parseDouble(jtf.getText()) == 0) {
jtf.setText("除數(shù)不能為零");
enter = false;
}
else
answerd /= Double.parseDouble(jtf.getText());
break;
default:
answerd = Double.parseDouble(jtf.getText());
System.out.println(answerd);
break;
}
jtf.setText("");
prekey = key = 0;
}
if(temp==jian){
switch (prekey) {
case 0:
answerd += Double.parseDouble(jtf.getText());
break;
case 1:
answerd -= Double.parseDouble(jtf.getText());
case 2:
answerd *= Double.parseDouble(jtf.getText());
case 3:
if (Double.parseDouble(jtf.getText()) == 0) {
jtf.setText("除數(shù)不能為零");
enter = false;
}
else
answerd /= Double.parseDouble(jtf.getText());
break;
default:
answerd = Double.parseDouble(jtf.getText());
break;
}
jtf.setText("");
prekey = key = 1;
}
if(temp==cheng){
switch (prekey) {
case 0:
answerd += Double.parseDouble(jtf.getText());
break;
case 1:
answerd -= Double.parseDouble(jtf.getText());
case 2:
answerd *= Double.parseDouble(jtf.getText());
case 3:
if (Double.parseDouble(jtf.getText()) == 0) {
jtf.setText("除數(shù)不能為零");
enter = false;
}
else
answerd /= Double.parseDouble(jtf.getText());
break;
default:
answerd = Double.parseDouble(jtf.getText());
break;
}
jtf.setText("");
prekey = key = 2;
}
if(temp==chu){
switch (prekey) {
case 0:
answerd += Double.parseDouble(jtf.getText());
break;
case 1:
answerd -= Double.parseDouble(jtf.getText());
case 2:
answerd *= Double.parseDouble(jtf.getText());
case 3:
if (Double.parseDouble(jtf.getText()) == 0) {
jtf.setText("除數(shù)不能為零");
enter = false;
}
else
answerd /= Double.parseDouble(jtf.getText());
break;
default:
answerd = Double.parseDouble(jtf.getText());
break;
}
jtf.setText("");
prekey = key = 3;
}
}
if(temp==dengyu enter==true){
if(prekey==5){
if(key==0){
answerd += vard;
jtf.setText(df.format(answerd));// 格式化一個(gè) double 值,以生成一個(gè)字符串。
}
if(key==1){
answerd -= vard;
jtf.setText(df.format(answerd));
}
if(key==2){
answerd *= vard;
jtf.setText(df.format(answerd));
}
if(key==3){
if(Double.parseDouble(jtf.getText())==0){
jtf.setText("除數(shù)不能為0");
enter = false;
}else {
answerd /= vard;
jtf.setText(df.format(answerd));
}
}
}else {
vard = Double.parseDouble(jtf.getText());
System.out.println(vard);
if(key==0){
prekey = -1;
answerd += Double.parseDouble(jtf.getText());
jtf.setText(df.format(answerd));
}
if(key==1){
prekey = -1;
answerd -= Double.parseDouble(jtf.getText());
jtf.setText(df.format(answerd));
}
if(key==2){
prekey = -1;
answerd *= Double.parseDouble(jtf.getText());
jtf.setText(df.format(answerd));
}
if(key==3){
prekey = -1;
if(Double.parseDouble(jtf.getText())==0){
jtf.setText("除數(shù)不能為0");
enter = false;
}else {
answerd /= Double.parseDouble(jtf.getText());
jtf.setText(df.format(answerd));
}
}
}
prekey=5;
}
if(temp==b1){
jtf.setText("");
enter=true;
}
//將按鈕挨個(gè)轉(zhuǎn)換為字符串
for(int i=0;ijb.length;i++){
if(temp==jb[i] enter==true){
jtf.setText(jtf.getText() + Integer.toString(i));
}
}
//**以下為MemuItem進(jìn)行事件
if(temp==copyM){
copy = jtf.getText();
}
if(temp==pasteM){
jtf.setText(copy);
}
if(temp==closeM){
dispose();
System.exit(0);
}
if(temp==gyM){
//JOptionPane.showMessageDialog(gyM,jsp);
JOptionPane.showMessageDialog(gyM, jsp);
}
if(temp == helpM){
JOptionPane.showMessageDialog(helpM,"使用“計(jì)算器”可以完成任意的通常借助手持計(jì)算器來(lái)完成的標(biāo)準(zhǔn)運(yùn)算。 \n “計(jì)算器”可用于基本的算術(shù)運(yùn)算,比如加減運(yùn)算等。 \n 同時(shí)它還具有科學(xué)計(jì)算器的功能,比如對(duì)數(shù)運(yùn)算和階乘運(yùn)算等。");
}
//**以上為MemuItem進(jìn)行事件
}
public static void main(String[] args) {
Calc cc = new Calc();
cc.setTitle("計(jì)算器 v1.0");
cc.setSize(400, 400);
cc.setBounds(300, 300, 300, 300);
cc.setVisible(true);
}
}
以前寫(xiě)的,給你了
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.text.DecimalFormat;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Calculator {
//計(jì)算器面板
private JFrame f = new JFrame("Calculator");
//輸入面扳
private JPanel inputPanel = new JPanel();
//加減乘除面板
private JPanel operationPanel = new JPanel();
//數(shù)字面板
private JPanel buttonsPanel = new JPanel();
//輸入數(shù)據(jù)文本框
private JTextField input = new JTextField(20);
//退格鍵
private JButton backspace = new JButton("BackSpace");
//清空
private JButton CE = new JButton("CE ");
//刪除
private JButton C = new JButton("C ");
//四則運(yùn)算符號(hào)鍵
private JButton add = new JButton("+");
private JButton sub = new JButton("-");
private JButton mul = new JButton("*");
private JButton div = new JButton("/");
//小數(shù)點(diǎn)
private JButton decimal = new JButton(".");
//等號(hào)
private JButton equal = new JButton("=");
//數(shù)字鍵
private JButton zero = new JButton("0");
private JButton one = new JButton("1");
private JButton two = new JButton("2");
private JButton three = new JButton("3");
private JButton four = new JButton("4");
private JButton five = new JButton("5");
private JButton six = new JButton("6");
private JButton seven = new JButton("7");
private JButton eight = new JButton("8");
private JButton nine = new JButton("9");
private String num1 = "";//保存第一個(gè)運(yùn)算數(shù)字
private String operator = "";//保存運(yùn)算符號(hào)
public static void main(String[] args) {
new Calculator();//new計(jì)算器實(shí)例
}
public Calculator(){
//添加組件,布局
inputPanel.add(input);
f.add(inputPanel, BorderLayout.NORTH);
operationPanel.add(backspace);
operationPanel.add(CE);
operationPanel.add(C);
f.add(operationPanel, BorderLayout.CENTER);
buttonsPanel.add(add);
buttonsPanel.add(sub);
buttonsPanel.add(mul);
buttonsPanel.add(div);
buttonsPanel.add(one);
buttonsPanel.add(two);
buttonsPanel.add(three);
buttonsPanel.add(zero);
buttonsPanel.add(four);
buttonsPanel.add(five);
buttonsPanel.add(six);
buttonsPanel.add(decimal);
buttonsPanel.add(seven);
buttonsPanel.add(eight);
buttonsPanel.add(nine);
buttonsPanel.add(equal);
buttonsPanel.setLayout(new GridLayout(4, 4));
f.add(buttonsPanel, BorderLayout.SOUTH);
//注冊(cè)各個(gè)組件監(jiān)聽(tīng)事件
backspace.addMouseListener(new OperationMouseListener());
CE.addMouseListener(new OperationMouseListener());
C.addMouseListener(new OperationMouseListener());
decimal.addMouseListener(new OperationMouseListener());
equal.addMouseListener(new OperationMouseListener());
//注冊(cè)四則運(yùn)算監(jiān)聽(tīng)
add.addMouseListener(new CalcMouseListener());
sub.addMouseListener(new CalcMouseListener());
mul.addMouseListener(new CalcMouseListener());
div.addMouseListener(new CalcMouseListener());
//注冊(cè)數(shù)字監(jiān)聽(tīng)事件
zero.addMouseListener(new NumberMouseListener());
one.addMouseListener(new NumberMouseListener());
two.addMouseListener(new NumberMouseListener());
three.addMouseListener(new NumberMouseListener());
four.addMouseListener(new NumberMouseListener());
five.addMouseListener(new NumberMouseListener());
six.addMouseListener(new NumberMouseListener());
seven.addMouseListener(new NumberMouseListener());
eight.addMouseListener(new NumberMouseListener());
nine.addMouseListener(new NumberMouseListener());
f.setVisible(true);
f.pack();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private class NumberMouseListener implements MouseListener{
public void mouseClicked(MouseEvent e) {
if(input.getText().trim().equals("0")){//如果文本框已經(jīng)是0,結(jié)果還是0
input.setText(((JButton)e.getSource()).getText().trim());
}else{//否則的話,把0添加到后面,譬如文本框是1,結(jié)果就為10
input.setText(input.getText().concat(((JButton)e.getSource()).getText().trim()));
}
}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
}
private class CalcMouseListener implements MouseListener{
//如果輸入的是運(yùn)算符號(hào),保存第一個(gè)結(jié)果和運(yùn)算符號(hào)
public void mouseClicked(MouseEvent e) {
num1 = input.getText().trim();input.setText("");
operator = ((JButton)e.getSource()).getText().trim();
}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
}
private class OperationMouseListener implements MouseListener{
public void mouseClicked(MouseEvent e) {
if(e.getSource() == backspace){//退格鍵,刪除一個(gè)直到?jīng)]有字符刪除
String inputText = input.getText();
if(inputText.length() 0){
input.setText(inputText.substring(0, inputText.length() - 1));
}
}else if(e.getSource() == C){
input.setText("0");//C,清空所有運(yùn)算數(shù)字和符號(hào)
num1 = "";
}else if(e.getSource() == CE){
input.setText("0");//CE--將文本框置為0
}else if(e.getSource() == decimal){
String text = input.getText().trim();
//如果按了小數(shù)點(diǎn),如果文本框已經(jīng)有小數(shù)點(diǎn),不做任何操作,否則在結(jié)果后面加上小數(shù)點(diǎn)
if(text.indexOf(".") == -1){
input.setText(text.concat("."));
}
}else if(e.getSource() == equal){
//如果是等號(hào)
if(!operator.trim().equals("")){
if(!input.getText().trim().equals("")){
double result = 0D;
if(operator.equals("+")){//執(zhí)行加法運(yùn)算
result = Double.parseDouble(num1) + Double.parseDouble(input.getText().trim());
}else if(operator.equals("-")){//減法運(yùn)算
result = Double.parseDouble(num1) - Double.parseDouble(input.getText().trim());
}else if(operator.equals("*")){//乘法運(yùn)算
result = Double.parseDouble(num1) * Double.parseDouble(input.getText().trim());
}else if(operator.equals("/")){//除法運(yùn)算
result = Double.parseDouble(num1) / Double.parseDouble(input.getText().trim());
}
//格式化最終結(jié)果,保留兩位小數(shù)點(diǎn)
input.setText(new DecimalFormat("0.00").format(result));
}
}
}
}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
}
}