欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

 更新時間:2021年07月19日 16:44:13   作者:杏黃的三葉草  
這篇文章主要為大家詳細(xì)介紹了用Java實現(xiàn)簡單計算器功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下

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

一 項目說明

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

實訓(xùn)要求:

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

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

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

(4)要有清零功能。

二、類設(shè)計

中綴表達(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)化為字符串輸出在文本框中。

四 運行與測試









五 分析與總結(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);
        // 對計算器整體框架的建立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);// 若是左括號就進(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í)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • SpringMVC 方法四種類型返回值總結(jié)(你用過幾種)

    SpringMVC 方法四種類型返回值總結(jié)(你用過幾種)

    這篇文章主要介紹了SpringMVC 方法四種類型返回值總結(jié)(你用過幾種),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2019-05-05
  • MyBatis入門程序

    MyBatis入門程序

    MyBatis是支持普通SQL查詢,存儲過程和高級映射的優(yōu)秀持久層框架。接下來本文給大家?guī)砹薓yBatis入門程序,感興趣的朋友一起學(xué)習(xí)吧
    2016-08-08
  • Java畢業(yè)設(shè)計之多用戶宿舍管理系統(tǒng)的實現(xiàn)

    Java畢業(yè)設(shè)計之多用戶宿舍管理系統(tǒng)的實現(xiàn)

    這篇文章主要介紹了基于Java實現(xiàn)的多用戶宿舍管理系統(tǒng),本文采用了jsp、servlet、jdbc等技術(shù),文中示例代碼講解詳細(xì),需要的可以參考一下
    2022-02-02
  • Java數(shù)組的去重

    Java數(shù)組的去重

    這篇文章主要介紹了Java數(shù)組去重,結(jié)合實例形式分析了Java針對數(shù)組的去重,需要的朋友可以參考下,希望能夠給你帶來幫助
    2021-10-10
  • 解決Maven靜態(tài)資源過濾問題

    解決Maven靜態(tài)資源過濾問題

    在我們使用Maven構(gòu)建項目的時候,會默認(rèn)過濾掉靜態(tài)資源,所以,需要手動來配置,本文就介紹一下Maven靜態(tài)資源過濾的問題解決,感興趣的可以了解一下
    2021-06-06
  • 解決RedisTemplate的key默認(rèn)序列化器的問題

    解決RedisTemplate的key默認(rèn)序列化器的問題

    這篇文章主要介紹了解決RedisTemplate的key默認(rèn)序列化器的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2021-03-03
  • SpringBoot整合Liquibase的示例代碼

    SpringBoot整合Liquibase的示例代碼

    本篇文章給大家介紹SpringBoot整合Liquibase的兩種情況分析,看似整合問題很簡單,但是很容易出錯,下面小編給大家介紹下整合步驟,感興趣的朋友跟隨小編一起看看吧
    2022-02-02
  • JavaWeb實現(xiàn)用戶登錄與注冊功能(服務(wù)器)

    JavaWeb實現(xiàn)用戶登錄與注冊功能(服務(wù)器)

    這篇文章主要介紹了JavaWeb實現(xiàn)用戶登錄與注冊功能,服務(wù)器部分的關(guān)鍵代碼實現(xiàn),文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2021-08-08
  • MyBatis注解式開發(fā)映射語句詳解

    MyBatis注解式開發(fā)映射語句詳解

    這幾年來注解開發(fā)越來越流行,Mybatis也可以使用注解開發(fā)方式,這樣我們就可以減少編寫Mapper映射文件了。我們先圍繞一些基本的CRUD來學(xué)習(xí),再學(xué)習(xí)復(fù)雜映射多表操作
    2023-02-02
  • Java基于虹軟實現(xiàn)人臉識別、人臉比對、活性檢測等

    Java基于虹軟實現(xiàn)人臉識別、人臉比對、活性檢測等

    本文主要介紹了Java基于虹軟實現(xiàn)人臉識別、人臉比對、活性檢測等,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2022-02-02

最新評論