用Java實現(xiàn)簡單計算器功能
本項目為大家分享了Java實現(xiàn)簡單計算器功能的具體代碼,供大家參考,具體內(nèi)容如下
一 項目說明

實訓(xùn)目的:掌握 Java GUI 開發(fā)中的布局管理和事件處理機制。
實訓(xùn)要求:
(1)要使用 java 的 GUI 設(shè)計出計算器界面。
(2)通過界面按鈕,可以實現(xiàn)整數(shù)或浮點數(shù)的四則運算,并能將結(jié)果顯示在界面中。
(3)計算可以有小數(shù)點,和正負整數(shù)的計算。
(4)要有清零功能。
二、類設(shè)計

中綴表達式的計算solution(String str)
用來中算后綴表達式的值,并將結(jié)果返回。準(zhǔn)備一個數(shù)字棧,一個運算符棧。大致的思路就是遇到,數(shù)字直接入數(shù)字棧,運算符看優(yōu)先級進行處理,將要入運算符棧的運算符與棧頂?shù)倪\算符進行比較,棧頂運算符優(yōu)先級比較高的話,則把棧頂?shù)倪\算符彈并且把數(shù)字棧的兩個數(shù)字進行彈出,進行運算,并且把結(jié)果再次放到數(shù)字棧中,最后剩下的就是最終結(jié)果。如果運算符優(yōu)先級比運算符棧頂?shù)男?,則把運算符進棧,最后把運算符都出棧。
計算加減乘除余caculateResult(char optemp, double num1, double num2)
通過傳入的optemp(表達式符號)參數(shù)。是什么符號就進行什么樣的運算
判斷符號的優(yōu)先級getOperlevel(char c)
先乘除后加減,通過0,1,2對運算符的優(yōu)先級進行標(biāo)記
三 項目實現(xiàn)設(shè)計
首先先設(shè)計一個GUI界面,先設(shè)置一個JFrame容器,容器中創(chuàng)建兩個面板和若干按鈕,先把按鈕要顯示的文字存入字符串?dāng)?shù)組,然后依次創(chuàng)建幾個按鈕。在設(shè)置一個文本框,用來接收用戶輸入的內(nèi)容,centerPanel.setLayout(new GridLayout(4, 4, 12, 16));設(shè)置中間面板的布局為網(wǎng)格布局,并指定該容器的行數(shù)和列數(shù)以及組件之間的水平、垂直間距。centerPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));為面板創(chuàng)建一個框,框的頭部為5像素,左為5像素,底部為5像素,右為5像素寬。再設(shè)置單行文本域的大小,字體,風(fēng)格和字號,然后為各按鈕設(shè)置監(jiān)聽器。定義一個StringBuffer類,用于保存觸發(fā)產(chǎn)生的內(nèi)容,在用txt.setText(r.toString());方法將內(nèi)容輸出在文本框中,clear按鈕觸發(fā)后,用r.delete(0,r.length());方法清空字符串中的內(nèi)容并將結(jié)果顯示在文本框中,“=”按鈕是把觸發(fā)器觸發(fā)的數(shù)字保存StringBuffer里面,然后用該類的toString()方法返回StringBuffer緩沖區(qū)中的字符對象,用String類型的變量接收,該字符串接收到的就是一個中綴表達式,創(chuàng)建一個類,該類用于將輸入的中綴表達式進行計算,把計算的結(jié)果返回給“=”按鈕觸發(fā)器中的result變量,把該變量轉(zhuǎn)化為字符串輸出在文本框中。
四 運行與測試









五 分析與總結(jié)
首先,我看到這個題的第一反應(yīng)是這個界面的布局要用到網(wǎng)格布局,開始我是想直接在觸發(fā)器里面實現(xiàn)相應(yīng)的加減乘除功能的,發(fā)現(xiàn)如果要計算四則運算有點困難,單個的加減乘除還是挺容易的,后面寫了一些代碼后,果斷刪了重寫,采用了數(shù)據(jù)結(jié)構(gòu)中的中綴表達式的計算算法(要用到棧),不過那個時候用的語言是C語言,所以關(guān)于棧的書寫就只能去百度了,之后我知道了棧和他的有關(guān)方法,自己也嘗試這寫了一段代碼進行了測試,更加熟練的掌握了棧的用法。
還順便看了一下廣大網(wǎng)友的代碼和算法,發(fā)現(xiàn)都大同小異,我自己也在他們寫的算法的基礎(chǔ)上寫了一段代碼,新增加了實現(xiàn)小數(shù)四則運算的功能,其中判斷運算符的優(yōu)先級那段代碼直接搬運了網(wǎng)上的代碼。
經(jīng)過測試,發(fā)現(xiàn)精度有一點問題,運算的結(jié)果有時是正確的,有時是無限接近正確結(jié)果(小數(shù)點后面的小數(shù)位太多了),還有就是實現(xiàn)不了負數(shù)的運算,但可以實現(xiàn)浮點數(shù)的四則運算。以我現(xiàn)在的水平,這個bug暫時還解決不了。所以就沒在修改了然后利用對象的調(diào)用把運算結(jié)果輸出在文本框里面。有一段時間這個程序的界面老是顯示不出來,控制臺console那里老是閃一下就滅了,我也非常納悶,之前我還可以顯示出來的啊,現(xiàn)在怎么就這樣的,百度了很久也沒找到答案,后面去請教同學(xué),才發(fā)現(xiàn)原來我的聊天窗口沒有設(shè)置為可見frame.setVisible(true);。所以一般在設(shè)置容器的時候,就在他的后面寫完他的所有屬性,不要寫完運行出錯了,才發(fā)現(xiàn)沒有寫。`
Calculater:
package com.itcase_eight;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DateFormat;
import java.util.Date;
/**
* @author 羅志剛
* @date 2020/12/16 22:09
*/
public class Calculater {
public static void createAndShowGUI() {
Date date=new Date();
DateFormat format=DateFormat.getDateInstance(DateFormat.SHORT);
// 對計算器整體框架的建立start
JFrame f = new JFrame("計算器");// 窗口
JPanel centerPanel = new JPanel(); // 中間面板
JPanel startPanel=new JPanel();
// 初始化功能鍵
JButton left=new JButton("(");
JLabel data=new JLabel(format.format(date),JLabel.CENTER);
data.setFont(new Font("Times New Roman",Font.BOLD,17));
JButton clear=new JButton("Clear");
JButton right=new JButton(")");
String button[] = { "7", "8", "9", "/", "4", "5", "6", "*", "1", "2", "3", "-", ".", "0", "=", "+"};
JButton but0 = new JButton(button[0]);
JButton but1 = new JButton(button[1]);
JButton but2 = new JButton(button[2]);
JButton but3 = new JButton(button[3]);
JButton but4 = new JButton(button[4]);
JButton but5 = new JButton(button[5]);
JButton but6 = new JButton(button[6]);
JButton but7 = new JButton(button[7]);
JButton but8 = new JButton(button[8]);
JButton but9 = new JButton(button[9]);
JButton but10 = new JButton(button[10]);
JButton but11 = new JButton(button[11]);
JButton but12 = new JButton(button[12]);
JButton but13 = new JButton(button[13]);
JButton but14 = new JButton(button[14]);
JButton but15 = new JButton(button[15]);
// 單行輸入文本框
JTextField txt = new JTextField();
// 使用網(wǎng)格布局方式
centerPanel.setLayout(new GridLayout(5, 4, 12, 16)); // 左右上下間隔
centerPanel.add(left);
centerPanel.add(clear);
centerPanel.add(right);
centerPanel.add(data);
centerPanel.add(but0);
centerPanel.add(but1);
centerPanel.add(but2);
centerPanel.add(but3);
centerPanel.add(but4);
centerPanel.add(but5);
centerPanel.add(but6);
centerPanel.add(but7);
centerPanel.add(but8);
centerPanel.add(but9);
centerPanel.add(but10);
centerPanel.add(but11);
centerPanel.add(but12);
centerPanel.add(but13);
centerPanel.add(but14);
centerPanel.add(but15);
centerPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
// 設(shè)置容器大小
txt.setPreferredSize(new Dimension(465, 40));
// 設(shè)置字體,風(fēng)格和字號
txt.setFont(new Font("宋體", Font.PLAIN, 28));
f.add(startPanel);
f.add(txt, BorderLayout.NORTH); // 將單行文本框添加到窗口的 北部
f.add(centerPanel, BorderLayout.SOUTH); // 將中間面板添加到窗口的南部
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);// 點X關(guān)閉窗口
f.setLocation(400, 200); // 初始化時定位
f.setSize(500, 300);
// 展示JFrame窗口
f.setVisible(true);
f.setResizable(false); // 禁止拖曳改變窗口大小
f.pack(); // 讓窗口的大小自適應(yīng)
// 對計算器整體框架的建立end
// 為按鈕事件添加自定義監(jiān)聽器start
StringBuffer r=new StringBuffer();
but0.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
r.append("7");
txt.setText(r.toString());
}
});
but1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
r.append("8");
txt.setText(r.toString());
}
});
but2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
r.append("9");
txt.setText(r.toString());
}
});
but4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
r.append("4");
txt.setText(r.toString());
}
});
but5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
r.append("5");
txt.setText(r.toString());
}
});
but6.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
r.append("6");
txt.setText(r.toString());
}
});
left.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
r.append("(");
txt.setText(r.toString());
}
});
right.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
r.append(")");
txt.setText(r.toString());
}
});
but8.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
r.append("1");
txt.setText(r.toString());
}
});
but9.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
r.append("2");
txt.setText(r.toString());
}
});
but10.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
r.append("3");
txt.setText(r.toString());
}
});
but13.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
r.append("0");
txt.setText(r.toString());
}
});
but15.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
r.append("+");
txt.setText(r.toString());
}
});
but3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
r.append("/");
txt.setText(r.toString());
}
});
but7.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
r.append("*");
txt.setText(r.toString());
}
});
but12.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
r.append(".");
txt.setText(r.toString());
}
});
but11.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
r.append("-");
txt.setText(r.toString());
}
});
clear.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
r.delete(0,r.length()); //清空字符串中的內(nèi)容
txt.setText(r.toString()); //將結(jié)果顯示在文本框中
}
});
but14.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
r.append("=");
String str=r.toString();
txt.setText("");
double result= Computer.solution(str);
String string=String.valueOf(result);
r.delete(0,r.length());
r.append(string);
txt.setText(string);
}
});
}
public static void main(String[] args) {
SwingUtilities.invokeLater(Calculater::createAndShowGUI);
}
}
Computer類:
package com.itcase_eight;
import java.util.Stack;
/**
* @author 羅志剛
* @date 2020/12/16 22:05
*/
public class Computer {
public static double solution(String str) {
Stack<Double> numStack = new Stack<>();
Stack<Character> signalStack = new Stack<>();
int index = 0;// 記錄已經(jīng)執(zhí)行的符號數(shù)
int len = str.length();
while (index < len) {
char c = str.charAt(index); // 取出這一步的符號
if (c == '(') {
signalStack.push(c);// 若是左括號就進棧
}
// 否則要先判斷優(yōu)先級
else if (c == '+' || c == '-' || c == '*' || c == '/') {
int currOperLevel = getOperlevel(c);// 當(dāng)前符號的優(yōu)先級
while (true) {
int stackOperLevel = 0;// 棧頂元素的優(yōu)先級
if (!signalStack.isEmpty()) {
Object obj = signalStack.peek();
stackOperLevel = getOperlevel((char) obj);
}
// 若當(dāng)前元素優(yōu)先級大于棧頂元素的優(yōu)先級則入棧
if (currOperLevel > stackOperLevel) {
signalStack.push(c);
break;// 直到讓比自己優(yōu)先級高的符號都出棧運算了再把自己進棧
} else {// 不能入棧就進行計算
try {
char optemp = '0';
double num1 = 0;
double num2 = 0;
if (!signalStack.isEmpty()) {
optemp = (char) signalStack.pop();// 取出優(yōu)先級大的那個符號
}
if (!numStack.isEmpty()) {
num1 = (double) numStack.pop();
num2 = (double) numStack.pop();// 取出數(shù)據(jù)棧中的兩個數(shù)
}
numStack.push(caculateResult(optemp, num2, num1));// 將算出來的結(jié)果數(shù)據(jù)再次進入數(shù)據(jù)棧
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
} else if (c == ')') {// 右括號就返回棧頂元素,右括號是不進棧的
while (true) {
char theop = (char) signalStack.pop();
if (theop == '(') {
break;
} else {
try {
double num1 = (double) numStack.pop();
double num2 = (double) numStack.pop();
numStack.push(caculateResult(theop, num2, num1));// 運算括號內(nèi)的內(nèi)容
} catch (Exception e) {
e.printStackTrace();
}
}
}
} else if (c >= '0' && c <= '9') {
int tempIndex = index + 1;
while (tempIndex < len) {
char temp = str.charAt(tempIndex);// 取字符串中處于當(dāng)前字符的下一位
if ((temp >= '0' && temp <= '9') || temp == '.') {
tempIndex++;// 若為數(shù)字則繼續(xù)向后取
} else {
break;// 證明數(shù)字去完
}
}
String numstr = str.substring(index, tempIndex);// 截取這個字符串則為兩個符號之間的數(shù)字
try {
double numnum = Double.parseDouble(numstr);// 將數(shù)字轉(zhuǎn)換成整型便于運算
numStack.push(numnum);
index = tempIndex - 1;
} catch (Exception e) {
e.printStackTrace();
}
}
index++;
}
// 檢查符號棧是否為空
while (true) {
Object obj = null;
if (signalStack.isEmpty() == false) {
obj = signalStack.pop();
}
if (obj == null) {
break;// 為空證明運算已結(jié)束
} else {// 不為空就出棧運算
char opterTemp = (char) obj;
double num1 = (double) numStack.pop();
double num2 = (double) numStack.pop();
numStack.push(caculateResult(opterTemp, num2, num1));
}
}
double result = 0;
try {
result = (double) numStack.pop();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return result;
}
//計算加減乘除余
private static Double caculateResult(char optemp, double num1, double num2) {
switch (optemp) {
case '+':
return num1 + num2;
case '-':
return num1 - num2;
case '*':
return num1 * num2;
case '/':
return num1 / num2;
}
return 0.0;
}
//返回符號優(yōu)先級
private static int getOperlevel(char c) {
switch (c) {
case '(':
return 0;
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
default:
return 0;
}
}
}
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
關(guān)于SpringCloud?Ribbon替換輪詢算法問題
Spring?Cloud?Ribbon是基于Netlix?Ribbon實現(xiàn)的一套客戶端負載均衡的工具。接下來通過本文給大家介紹SpringCloud?Ribbon替換輪詢算法問題,需要的朋友可以參考下2022-01-01
Java利用InputStream類實現(xiàn)文件讀取與處理
在Java開發(fā)中,輸入流(InputStream)是一個非常重要的概念,它涉及到文件讀寫、網(wǎng)絡(luò)傳輸?shù)榷鄠€方面,InputStream類是Java中輸入流的抽象基類,定義了讀取輸入流數(shù)據(jù)的方法,本文將以InputStream類為切入點,介紹Java中的輸入流概念及其應(yīng)用,需要的朋友可以參考下2023-11-11
Java使用JCommander實現(xiàn)解析命令行參數(shù)
jcommander?是一個只有幾十?kb?的?Java?命令行參數(shù)解析工具,可以通過注解的方式快速實現(xiàn)命令行參數(shù)解析,本文就來和大家介紹一下JCommander是如何解析命令行參數(shù)吧2023-06-06
Java消息摘要算法MAC實現(xiàn)與應(yīng)用完整示例
這篇文章主要介紹了Java消息摘要算法MAC實現(xiàn)與應(yīng)用,結(jié)合完整實例形式分析了java消息摘要算法MAC的概念、原理、實現(xiàn)方法及相關(guān)操作注意事項,需要的朋友可以參考下2019-09-09
配置了jdk的環(huán)境idea卻提示找不到j(luò)dk解決辦法
在使用Java編程語言進行開發(fā)時,IDEA是一個非常流行和強大的集成開發(fā)環(huán)境,這篇文章主要給大家介紹了關(guān)于配置了jdk的環(huán)境idea卻提示找不到j(luò)dk的解決辦法,需要的朋友可以參考下2023-12-12

