亚洲精品久久久中文字幕-亚洲精品久久片久久-亚洲精品久久青草-亚洲精品久久婷婷爱久久婷婷-亚洲精品久久午夜香蕉

您的位置:首頁技術(shù)文章
文章詳情頁

用Java實現(xiàn)簡單計算器功能

瀏覽:42日期:2022-08-08 18:38:08

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

一 項目說明

用Java實現(xiàn)簡單計算器功能

實訓(xùn)目的:掌握 Java GUI 開發(fā)中的布局管理和事件處理機制。

實訓(xùn)要求:

(1)要使用 java 的 GUI 設(shè)計出計算器界面。

(2)通過界面按鈕,可以實現(xiàn)整數(shù)或浮點數(shù)的四則運算,并能將結(jié)果顯示在界面中。

(3)計算可以有小數(shù)點,和正負(fù)整數(shù)的計算。

(4)要有清零功能。

二、類設(shè)計

用Java實現(xiàn)簡單計算器功能

中綴表達(dá)式的計算solution(String str)用來中算后綴表達(dá)式的值,并將結(jié)果返回。準(zhǔn)備一個數(shù)字棧,一個運算符棧。大致的思路就是遇到,數(shù)字直接入數(shù)字棧,運算符看優(yōu)先級進(jìn)行處理,將要入運算符棧的運算符與棧頂?shù)倪\算符進(jìn)行比較,棧頂運算符優(yōu)先級比較高的話,則把棧頂?shù)倪\算符彈并且把數(shù)字棧的兩個數(shù)字進(jìn)行彈出,進(jìn)行運算,并且把結(jié)果再次放到數(shù)字棧中,最后剩下的就是最終結(jié)果。如果運算符優(yōu)先級比運算符棧頂?shù)男。瑒t把運算符進(jìn)棧,最后把運算符都出棧。計算加減乘除余caculateResult(char optemp, double num1, double num2)通過傳入的optemp(表達(dá)式符號)參數(shù)。是什么符號就進(jìn)行什么樣的運算判斷符號的優(yōu)先級getOperlevel(char c)先乘除后加減,通過0,1,2對運算符的優(yōu)先級進(jìn)行標(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類型的變量接收,該字符串接收到的就是一個中綴表達(dá)式,創(chuàng)建一個類,該類用于將輸入的中綴表達(dá)式進(jìn)行計算,把計算的結(jié)果返回給“=”按鈕觸發(fā)器中的result變量,把該變量轉(zhuǎn)化為字符串輸出在文本框中。

四 運行與測試

用Java實現(xiàn)簡單計算器功能用Java實現(xiàn)簡單計算器功能用Java實現(xiàn)簡單計算器功能用Java實現(xiàn)簡單計算器功能用Java實現(xiàn)簡單計算器功能用Java實現(xiàn)簡單計算器功能用Java實現(xiàn)簡單計算器功能用Java實現(xiàn)簡單計算器功能用Java實現(xiàn)簡單計算器功能

五 分析與總結(jié)

首先,我看到這個題的第一反應(yīng)是這個界面的布局要用到網(wǎng)格布局,開始我是想直接在觸發(fā)器里面實現(xiàn)相應(yīng)的加減乘除功能的,發(fā)現(xiàn)如果要計算四則運算有點困難,單個的加減乘除還是挺容易的,后面寫了一些代碼后,果斷刪了重寫,采用了數(shù)據(jù)結(jié)構(gòu)中的中綴表達(dá)式的計算算法(要用到棧),不過那個時候用的語言是C語言,所以關(guān)于棧的書寫就只能去百度了,之后我知道了棧和他的有關(guān)方法,自己也嘗試這寫了一段代碼進(jì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)不了負(fù)數(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);// 對計算器整體框架的建立startJFrame 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)聽器startStringBuffer 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);// 若是左括號就進(jìn)棧 } // 否則要先判斷優(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)先級高的符號都出棧運算了再把自己進(jìn)棧 } else {// 不能入棧就進(jìn)行計算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ù)再次進(jìn)入數(shù)據(jù)棧} catch (Exception e) { // TODO: handle exception e.printStackTrace();} }} } else if (c == ’)’) {// 右括號就返回棧頂元素,右括號是不進(jìn)棧的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í)有所幫助,也希望大家多多支持好吧啦網(wǎng)。

標(biāo)簽: Java
相關(guān)文章:
主站蜘蛛池模板: 精品一区二区高清在线观看 | 国产精品玖玖玖在线观看 | 在线看一区 | 精品视频入口 | 91极品尤物| 免费观看a级毛片在线播放 免费观看a级片 | 麻豆剧场| 日本在线一区二区 | 白眉大侠320回在线收听 | 久久ri精品高清一区二区三区 | 亚洲欧美日韩中文字幕久久 | 久青草国产手机在线视频 | 国产成版人视频网站免费下 | 性生活视频黄色 | 中文字幕一区在线播放 | 国语对白avxxxooo | 亚洲精品综合一区在线 | 一区二区在线观看视频在线 | 国产一区精品在线 | 国产人成午夜免费噼啪视频 | 男人看片资源 | 九九精品免费观看在线 | 6080yy 久久 亚洲 日本 | 国产精品v欧美精品v日韩 | a级午夜毛片免费一区二区 a级午夜理论免费毛片 | 全黄毛片 | 国产一级aa大片毛片 | 91madou传媒在线观看 | 国产αv | 欧美一级黄色大片 | 中国一级毛片在线观看 | 国产香蕉网 | 亚洲精品成人一区二区www | 日韩一级片在线 | 欧美成人亚洲高清在线观看 | 九九精品视频一区在线 | 国产成人免费高清视频网址 | 无人精品乱码一区二区三区 | 婷婷草 | 久久国产精品最新一区 | 欧美成人禁片在线观看俄罗斯 |