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

如何用Java的swing編寫簡(jiǎn)單計(jì)算器

 更新時(shí)間:2023年12月27日 15:27:23   作者:cdh4119_  
這篇文章主要給大家介紹了關(guān)于如何用Java的swing編寫簡(jiǎn)單計(jì)算器的相關(guān)資料,通過(guò)本文可以設(shè)計(jì)一個(gè)圖形界面的簡(jiǎn)易計(jì)算器,完成簡(jiǎn)單的算術(shù)運(yùn)算符,可以完成加法、減法、乘法、除法和取余運(yùn)算,需要的朋友可以參考下

前言

本文用Javaswing來(lái)實(shí)現(xiàn)一個(gè)簡(jiǎn)單計(jì)算器,主要內(nèi)容為圖形用戶界面GUI的實(shí)現(xiàn)以及運(yùn)算表達(dá)式核心算法的設(shè)計(jì)編寫。

程序運(yùn)行環(huán)境為Windows10 ,編譯環(huán)境為IntelliJ IDEA Community Edition 2022.2.3

一、具體功能:

1、:輸入,輸出

 輸入:允許輸入帶有括號(hào)的完整計(jì)算式(例 8*(4-95)+5÷2*e-pi)
 輸出:輸出Double類型的結(jié)果
 輸出:整個(gè)運(yùn)算表達(dá)式并保存于歷史記錄中

2、:功能 

 基本的加,減,乘,除,四則運(yùn)算
 平方運(yùn)算
 開(kāi)方運(yùn)算
 求余運(yùn)算

最終界面如下圖:

除了常規(guī)的數(shù)字按鈕和運(yùn)算符,還有兩個(gè)常數(shù)e,pi(π),清空鍵AC,括號(hào)運(yùn)算符(),平方(x^x)和開(kāi)方(sqrt)運(yùn)算符,輸入顯示框以及歷史記錄文本框,文本框的垂直滾動(dòng)條和水平滾動(dòng)條。 

二、主要思想:

1:中綴表達(dá)式轉(zhuǎn)為后綴表達(dá)式

準(zhǔn)備:

①后綴表達(dá)式隊(duì)列:postQueue,用于存儲(chǔ)逆波蘭表達(dá)式(其實(shí)不用隊(duì)列排序直接輸出也行)
②操作符棧:opStack,對(duì)用戶輸入的操作符進(jìn)行處理,用于存儲(chǔ)運(yùn)算符

算法思想:

從左向右依次讀取算術(shù)表達(dá)式的元素X,分以下情況進(jìn)行不同的處理:
(1)如果X是操作數(shù),直接入隊(duì)
(2)如果X是運(yùn)算符,再分以下情況:
a)如果棧為空,直接入棧。
b)如果X==”(“,直接入棧。
c)如果X==”)“,則將棧里的元素逐個(gè)出棧,并入隊(duì)到后綴表達(dá)式隊(duì)列中,直到第一個(gè)配對(duì)的”(”出棧。(注:“(”和“)”都不 入隊(duì))
d)如果是其他操作符(+ - * /),則和棧頂元素進(jìn)行比較優(yōu)先級(jí)。 如果棧頂元素的優(yōu)先級(jí)大于等于X,則出棧并把棧中彈出的元素入隊(duì),直到棧頂元素的優(yōu)先級(jí)小于X或者棧為空。彈出完這些元素后,才將遇到的操作符壓入到棧中。
(3)最后將棧中剩余的操作符全部入隊(duì)。

示意圖:

2、計(jì)算后綴表達(dá)式

準(zhǔn)備:

需要用到一個(gè)結(jié)果棧Res_Stack :用于存放計(jì)算的中間過(guò)程的值和最終結(jié)果

 算法思想:

1、從左開(kāi)始向右遍歷后綴表達(dá)式的元素。
2、如果取到的元素是操作數(shù),直接入棧Res_Stack,如果是運(yùn)算符,從棧中彈出2個(gè)數(shù)進(jìn)行運(yùn)算,然后把運(yùn)算結(jié)果入棧
3、當(dāng)遍歷完后綴表達(dá)式時(shí),計(jì)算結(jié)果就保存在棧里了。

示意圖:

三、結(jié)果測(cè)試

分析: 

1、可實(shí)現(xiàn)基本四則運(yùn)算及平方、開(kāi)方、求余運(yùn)算。

2、運(yùn)算表達(dá)式可顯示于輸入界面并保存于歷史記錄欄

3、輸入界面和歷史記錄欄皆可實(shí)現(xiàn)不斷字自動(dòng)換行功能以及滾動(dòng)條功能

4、不足之處:進(jìn)行平方和開(kāi)方運(yùn)算時(shí)其保存在歷史記錄中的表達(dá)式會(huì)出現(xiàn)兩個(gè)等號(hào)及兩個(gè)結(jié)果。

四、完整源代碼

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.*;
import java.util.stream.Collectors;

public class Calculator extends JFrame implements ActionListener {
    Calculator() {
        init();
    }

    /**
     * 定義按鈕
     */
    private JTextField textField1;
    private JTextArea textField2;
    private JButton buttonzuo;//(
    private JButton buttonyou;//)
    private JButton buttonC;//c
    private JButton buttonCE;//CE
    private JButton buttondele;//<- 刪除
    private JButton buttonDiv;//÷
    private JButton button7;//7
    private JButton button8;//8
    private JButton button9;//9
    private JButton buttonAdd;//+
    private JButton button4;//4
    private JButton button5;//5
    private JButton button6;//6
    private JButton buttonSub;//-
    private JButton button1;//1
    private JButton button2;//2
    private JButton button3;//3
    private JButton buttonMul;//x
    private JButton buttonequl;//=
    private JButton button0;//0
    private JButton buttonPoint;//.

    public void init() {
        JFrame frame = new JFrame("The Calculator Of 崔登輝");                  //普通窗口頂層容器   創(chuàng)建標(biāo)題為“計(jì)算器”;
        frame.setLayout(null);                                                   //設(shè)置使用特定的布局管理器;
        //單選項(xiàng)按鈕
        //按鍵的排版以及設(shè)計(jì)需要提前考慮整體的布局合理性,不可出現(xiàn)按鍵重疊;為了保證美觀又需要考慮排版整齊;
        //放置數(shù)字0
        button0 = new JButton("0");                                         //注:在給按鍵命名時(shí)要根據(jù)按鍵的大小,否則按鍵上的標(biāo)注無(wú)法完全顯示;
        button0.setBounds(100, 400, 110, 50);
        frame.add(button0);
        //放置數(shù)字1
        button1 = new JButton("1");
        button1.setBounds(40, 340, 50, 50);
        frame.add(button1);
        //放置數(shù)字2
        button2 = new JButton("2");
        button2.setBounds(100, 340, 50, 50);
        frame.add(button2);
        //放置數(shù)字3
        button3 = new JButton("3");
        button3.setBounds(160, 340, 50, 50);
        frame.add(button3);
        //放置數(shù)字4
        button4 = new JButton("4");
        button4.setBounds(40, 280, 50, 50);
        frame.add(button4);
        //放置數(shù)字5
        button5 = new JButton("5");
        button5.setBounds(100, 280, 50, 50);
        frame.add(button5);
        //放置數(shù)字6
        button6 = new JButton("6");
        button6.setBounds(160, 280, 50, 50);
        frame.add(button6);
        //放置數(shù)字7
        button7 = new JButton("7");
        button7.setBounds(40, 220, 50, 50);
        frame.add(button7);
        //放置數(shù)字8
        button8 = new JButton("8");
        button8.setBounds(100, 220, 50, 50);
        frame.add(button8);
        //放置數(shù)字9
        button9 = new JButton("9");
        button9.setBounds(160, 220, 50, 50);
        frame.add(button9);
        //放置 .
        buttonPoint = new JButton(".");                                                   //text:為自動(dòng)生成的參數(shù)的解釋詞
        buttonPoint.setBounds(40, 400, 50, 50);                            //自動(dòng)補(bǔ)齊的參數(shù)解釋詞
        frame.add(buttonPoint);
        //放置 +
        buttonAdd = new JButton("+");
        buttonAdd.setBounds(220, 400, 50, 50);
        frame.add(buttonAdd);
        //放置 -
        buttonSub = new JButton("-");
        buttonSub.setBounds(220, 340, 50, 50);
        frame.add(buttonSub);
        //放置 *
        buttonMul = new JButton("*");
        buttonMul.setBounds(220, 280, 50, 50);
        frame.add(buttonMul);
        //放置 /
        buttonDiv = new JButton("/");
        buttonDiv.setBounds(220, 220, 50, 50);
        frame.add(buttonDiv);
        //放置 =
        buttonequl = new JButton("=");
        buttonequl.setBounds(280, 340, 110, 110);
        frame.add(buttonequl);
        //退位鍵
        buttondele = new JButton("B");
        buttondele.setBounds(280, 220, 110, 110);
        frame.add(buttondele);
        //放置左括號(hào)(
        buttonzuo = new JButton("(");
        buttonzuo.setBounds(40, 160, 80, 50);
        frame.add(buttonzuo);
        //放置右括號(hào))
        buttonyou = new JButton(")");
        buttonyou.setBounds(130, 160, 80, 50);
        frame.add(buttonyou);
        //放置C  消除所有輸入
        buttonC = new JButton("C");
        buttonC.setBounds(220, 160, 80, 50);
        frame.add(buttonC);
        //放置CE 消除當(dāng)前輸入
        buttonCE = new JButton("CE");
        buttonCE.setBounds(310, 160, 80, 50);
        frame.add(buttonCE);
        //添加表達(dá)式文本框 用以輸入計(jì)算公式
        textField1 = new JTextField();           //文本框
        textField1.setBounds(40, 20, 350, 60);
        frame.add(textField1);
        textField2 = new JTextArea();
        textField2.setBounds(400, 20, 280, 430);
        frame.add(textField2);


        textField1.addActionListener(this);
        buttonzuo.addActionListener(this);
        buttonyou.addActionListener(this);
        buttonC.addActionListener(this);
        buttonCE.addActionListener(this);
        buttondele.addActionListener(this);
        buttonDiv.addActionListener(this);
        button7.addActionListener(this);
        button8.addActionListener(this);
        button9.addActionListener(this);
        buttonAdd.addActionListener(this);
        button4.addActionListener(this);
        button5.addActionListener(this);
        button6.addActionListener(this);
        buttonSub.addActionListener(this);
        button1.addActionListener(this);
        button2.addActionListener(this);
        button3.addActionListener(this);
        buttonMul.addActionListener(this);
        buttonequl.addActionListener(this);
        button0.addActionListener(this);
        buttonPoint.addActionListener(this);

        frame.setBounds(0, 0, 700, 520);       //設(shè)置整個(gè)圖形窗口的大小;(通過(guò)窗口名調(diào)用)
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);    //setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE),當(dāng)點(diǎn)擊窗口的關(guān)閉按鈕時(shí)退出程序(沒(méi)有這一句,程序不會(huì)退出)
        frame.setVisible(true);
    }

    String str = null;
    int pointbook = 0;
    int equalbook = 0;
    int zuonum = 0;
    int younum = 0;
    int equnum = 0;


    public void actionPerformed(ActionEvent e) {
        if (equnum == 1) {
            textField1.setText("0");
            equnum = 0;
        }
        //按0
        if (e.getSource().equals(button0)) {
            str = textField1.getText();
            if (str.length() > 16 || str.equals("0") || equalbook == 1) {

            } else {
                textField1.setText(str + "0");
            }
        }
        //按1
        if (e.getSource().equals(button1)) {
            str = textField1.getText();
            if (str.length() > 16 || equalbook == 1) {

            } else if (str.equals("0") || str.equals("")) {
                textField1.setText("1");
            } else {
                textField1.setText(str + "1");
            }
        }
        //當(dāng)按鈕為2時(shí)
        if (e.getSource().equals(button2)) {
            str = textField1.getText();
            if (str.length() > 16 || equalbook == 1) {
            } else if (str.equals("0") || str.equals("")) {
                textField1.setText("2");
            } else {
                textField1.setText(str + "2");
            }
        }
        //當(dāng)按鈕為3時(shí)
        if (e.getSource().equals(button3)) {
            str = textField1.getText();
            if (str.length() > 16 || equalbook == 1) {
            } else if (str.equals("0") || str.equals("")) {
                textField1.setText("3");
            } else {
                textField1.setText(str + "3");
            }
        }
        //當(dāng)按鈕為4時(shí)
        if (e.getSource().equals(button4)) {
            str = textField1.getText();
            if (str.length() > 16 || equalbook == 1) {
            } else if (str.equals("0") || str.equals("")) {
                textField1.setText("4");
            } else {
                textField1.setText(str + "4");
            }
        }
        //當(dāng)按鈕為5時(shí)
        if (e.getSource().equals(button5)) {
            str = textField1.getText();
            if (str.length() > 16 || equalbook == 1) {
            } else if (str.equals("0") || str.equals("")) {
                textField1.setText("5");
            } else {
                textField1.setText(str + "5");
            }
        }
        //當(dāng)按鈕為6時(shí)
        if (e.getSource().equals(button6)) {
            str = textField1.getText();
            if (str.length() > 16 || equalbook == 1) {
            } else if (str.equals("0") || str.equals("")) {
                textField1.setText("6");
            } else {
                textField1.setText(str + "6");
            }
        }
        //當(dāng)按鈕為7時(shí)
        if (e.getSource().equals(button7)) {
            str = textField1.getText();
            if (str.length() > 16 || equalbook == 1) {
            } else if (str.equals("0") || str.equals("")) {
                textField1.setText("7");
            } else {
                textField1.setText(str + "7");
            }
        }
        //當(dāng)按鈕為8時(shí)
        if (e.getSource().equals(button8)) {
            str = textField1.getText();
            if (str.length() > 16 || equalbook == 1) {
            } else if (str.equals("0") || str.equals("")) {
                textField1.setText("8");
            } else {
                textField1.setText(str + "8");
            }
        }
        //當(dāng)按鈕為9時(shí)
        if (e.getSource().equals(button9)) {
            str = textField1.getText();
            if (str.length() > 16 || equalbook == 1) {
            } else if (str.equals("0") || str.equals("")) {
                textField1.setText("9");
            } else {
                textField1.setText(str + "9");
            }
        }
        //當(dāng)按鈕為小數(shù)點(diǎn)時(shí)
        if (e.getSource().equals(buttonPoint)) {
            str = textField1.getText();
            if (str.length() > 15 || equalbook == 1) {                   //小數(shù)點(diǎn)位于操作數(shù)的最后一位不執(zhí)行操作;
            }
            if (pointbook == 0) {                                    //一個(gè)操作數(shù)僅能有一個(gè)小數(shù)點(diǎn),若已經(jīng)有小數(shù)點(diǎn)則不再添加小數(shù)點(diǎn);
                textField1.setText(str + ".");
                pointbook = 1;                                    //小數(shù)點(diǎn)判斷位置1;
            }
        }
        //每次輸入都是一個(gè)數(shù)字+運(yùn)算符,一起從數(shù)字文本框轉(zhuǎn)而輸入到表達(dá)式文本框中;
        //當(dāng)按鈕為加號(hào)時(shí)
        if (e.getSource().equals(buttonAdd)) {
            str = textField1.getText();                              //獲取運(yùn)算符前一個(gè)操作數(shù);
            char ch1[] = str.toCharArray();                        //把第一操作數(shù)連同+號(hào) 進(jìn)行字符串轉(zhuǎn)字符數(shù)組的操作 賦予ch1;
            int length1 = str.length() - 1;                        //length1獲取除+號(hào)外的第一操作數(shù)的位數(shù);
            if ((length1 == -1 || ch1[length1] != ')') && (str.equals("0") || str.equals("") || ch1[length1] == '.' || ch1[length1] == '+' || ch1[length1] == '-' || ch1[length1] == '*' || ch1[length1] == '/' || ch1[length1] == '(' || ch1[length1] == ')')) {
                //當(dāng)數(shù)字為空或?yàn)?(操作無(wú)意義);或數(shù)字的最后一位是小數(shù)點(diǎn)(未輸入完畢或輸入出錯(cuò),等待)
            } else {
                textField1.setText(str + "+");   //合并現(xiàn)有表達(dá)式和新增表達(dá)式
                // 這里解釋以下為什么s沒(méi)有提取到數(shù)字框里的符號(hào),因?yàn)檩斎敕?hào)時(shí)并沒(méi)有更新數(shù)字框,而是直接執(zhí)行一系列操作,數(shù)字框從未出現(xiàn)過(guò)運(yùn)算符;
            }
            pointbook = 0;
        }
        //當(dāng)按鈕為減號(hào)時(shí)
        if (e.getSource().equals(buttonSub)) {
            str = textField1.getText();
            char ch1[] = str.toCharArray();
            int length1 = str.length() - 1;
            if ((length1 == -1 || ch1[length1] != ')') && (ch1[length1] == '.' || ch1[length1] == '+' || ch1[length1] == '-' || ch1[length1] == '*' || ch1[length1] == '/' || ch1[length1] == '(' || ch1[length1] == ')')) {
            } else {
                textField1.setText(str + "-");
            }
            pointbook = 0;
        }
        //當(dāng)按鈕為乘號(hào)時(shí)
        if (e.getSource().equals(buttonMul)) {
            str = textField1.getText();
            char ch1[] = str.toCharArray();
            int length1 = str.length() - 1;
            if ((length1 == -1 || ch1[length1] != ')') && (str.equals("0") || str.equals("") || ch1[length1] == '.' || ch1[length1] == '+' || ch1[length1] == '-' || ch1[length1] == '*' || ch1[length1] == '/' || ch1[length1] == '(' || ch1[length1] == ')')) {
            } else {
                textField1.setText(str + "*");
            }
            pointbook = 0;
        }
        //當(dāng)按鈕為除號(hào)時(shí)
        if (e.getSource().equals(buttonDiv)) {
            str = textField1.getText();
            char ch1[] = str.toCharArray();
            int length1 = str.length() - 1;
            if ((length1 == -1 || ch1[length1] != ')') && (str.equals("0") || str.equals("") || ch1[length1] == '.' || ch1[length1] == '+' || ch1[length1] == '-' || ch1[length1] == '*' || ch1[length1] == '/' || ch1[length1] == '(' || ch1[length1] == ')')) {
            } else {
                textField1.setText(str + "/");
            }
            pointbook = 0;
        }
        //當(dāng)按鈕為左括號(hào)時(shí)
        if (e.getSource().equals(buttonzuo)) {
            str = textField1.getText();
            char ch[] = str.toCharArray();
            int length = str.length() - 1;
            if (length == -1 || ch[length] == '+' || ch[length] == '-' || ch[length] == '*' || ch[length] == '/') {
                //括號(hào)左邊是否有數(shù)或符號(hào)類別的判斷;
                textField1.setText(str + '(');     //滿足條件則加入左括號(hào);
                zuonum++;                                            //左括號(hào)數(shù)加一標(biāo)記;
            }
            if (length == -1 || ch[length] == '+' || ch[length] == '-' || ch[length] == '*' || ch[length] == '/')
                pointbook = 0;
            if (length == 0 || ch[length] == 0) {
                textField1.setText("(");
                zuonum++;
            }
        }
        //當(dāng)按鈕為右括號(hào)時(shí);
        if (e.getSource().equals(buttonyou)) {
            str = textField1.getText();
            char ch[] = str.toCharArray();
            int length = str.length() - 1;
            if (Character.isDigit(ch[length]) && zuonum > younum) {      //只有前面是數(shù)字的時(shí)候且左括號(hào)的數(shù)量大于右括號(hào)的數(shù)量的時(shí)候才能加右括號(hào);
                younum++;                                                 //右括號(hào)數(shù)加一標(biāo)記;
                textField1.setText(str + ')');
            }
            pointbook = 0;
        }
        //當(dāng)按下C鍵時(shí);
        if (e.getSource().equals(buttonC)) {
            textField1.setText("0");                  //置當(dāng)前數(shù)字框?yàn)?;
            zuonum = 0;                              //當(dāng)一次計(jì)算完成之后,只有按CE按鈕才能進(jìn)行新的計(jì)算,因?yàn)橐宄袠?biāo)志位否則會(huì)影響下一次操作;
            younum = 0;
            pointbook = 0;
            equalbook = 0;
            textField2.setText(" ");
        }
        //當(dāng)按鈕為CE時(shí),
        if (e.getSource().equals(buttonCE)) {
            textField1.setText("0");                       //清除當(dāng)前數(shù)字框中內(nèi)容;
            pointbook = 0;                                 //更新小數(shù)點(diǎn)狀態(tài)為0;
        }
        //當(dāng)按下B時(shí),
        if (e.getSource().equals(buttondele)) {
            str = textField1.getText();
            char []nums=str.toCharArray();
            if (nums[str.length()-1]=='('){
                zuonum--;
            }
            str = str.substring(0, str.length() - 1);
            textField1.setText(str);
        }
        //當(dāng)按下=時(shí),
        if (e.getSource().equals(buttonequl)) {
            str = textField1.getText();
            if (zuonum != younum) {
                textField1.setText("關(guān)系式錯(cuò)誤。");
            } else {
                ans(str);
            }
            String s = str + "=" + textField1.getText();
            textField2.setText(s + "\r\n" + textField2.getText());                //將表達(dá)式存放在歷史記錄里。
            equnum = 1;
        }
    }


    /**
     * 提前將 符號(hào)的優(yōu)先級(jí)定義好
     */
    private static final Map<Character, Integer> basic = new HashMap<Character, Integer>();

    static {
        basic.put('-', 1);
        basic.put('+', 1);
        basic.put('*', 2);
        basic.put('/', 2);
        basic.put('(', 0);//在運(yùn)算中  ()的優(yōu)先級(jí)最高,但是此處因程序中需要 故設(shè)置為0
    }


    public void ans(String str) {
        String a = toSuffix(str);//傳入 一串 算數(shù)公式
        textField1.setText(dealEquation(a));

    }

    /**
     * 將  中綴表達(dá)式  轉(zhuǎn)化為  后綴表達(dá)式
     */
    public String toSuffix(String infix) {
        List<String> queue = new ArrayList<String>();                                    //定義隊(duì)列  用于存儲(chǔ) 數(shù)字  以及最后的  后綴表達(dá)式
        List<Character> stack = new ArrayList<Character>();                             //定義棧    用于存儲(chǔ)  運(yùn)算符  最后stack中會(huì)被 彈空

        char[] charArr = infix.trim().toCharArray();                                    //字符數(shù)組  用于拆分?jǐn)?shù)字或符號(hào)
        String standard = "*/+-()";                                                        //判定標(biāo)準(zhǔn) 將表達(dá)式中會(huì)出現(xiàn)的運(yùn)算符寫出來(lái)
        char ch = '&';                                                                    //在循環(huán)中用來(lái)保存 字符數(shù)組的當(dāng)前循環(huán)變量的  這里僅僅是初始化一個(gè)值  沒(méi)有意義
        int len = 0;                                                                    //用于記錄字符長(zhǎng)度 【例如100*2,則記錄的len為3 到時(shí)候截取字符串的前三位就是數(shù)字】
        for (int i = 0; i < charArr.length; i++) {                                        //開(kāi)始迭代

            ch = charArr[i];                                                            //保存當(dāng)前迭代變量
            if (Character.isDigit(ch)) {                                                    //如果當(dāng)前變量為 數(shù)字
                len++;
            } else if (Character.isLetter(ch)) {                                            //如果當(dāng)前變量為  字母
                len++;
            } else if (ch == '.') {                                                        //如果當(dāng)前變量為  .  會(huì)出現(xiàn)在小數(shù)里面
                len++;
            } else if (Character.isSpaceChar(ch)) {                                        //如果當(dāng)前變量為 空格  支持表達(dá)式中有空格出現(xiàn)
                if (len > 0) {                                                            //若為空格 代表 一段結(jié)束 ,就可以往隊(duì)列中  存入了  【例如100 * 2  100后面有空格 就可以將空格之前的存入隊(duì)列了】
                    queue.add(String.valueOf(Arrays.copyOfRange(charArr, i - len, i)));    //往 隊(duì)列存入 截取的 字符串
                    len = 0;                                                            //長(zhǎng)度置空
                }
                continue;                                                                //如果空格出現(xiàn),則一段結(jié)束  跳出本次循環(huán)
            } else if (standard.indexOf(ch) != -1) {                                        //如果是上面標(biāo)準(zhǔn)中的 任意一個(gè)符號(hào)
                if (len > 0) {                                                            //長(zhǎng)度也有
                    queue.add(String.valueOf(Arrays.copyOfRange(charArr, i - len, i)));    //說(shuō)明符號(hào)之前的可以截取下來(lái)做數(shù)字
                    len = 0;                                                            //長(zhǎng)度置空
                }
                if (ch == '(') {                                                            //如果是左括號(hào)
                    stack.add(ch);                                                        //將左括號(hào) 放入棧中
                    continue;                                                            //跳出本次循環(huán)  繼續(xù)找下一個(gè)位置
                }
                if (!stack.isEmpty()) {                                                    //如果棧不為empty
                    int size = stack.size() - 1;                                        //獲取棧的大小-1  即代表?xiàng)W詈笠粋€(gè)元素的下標(biāo)
                    boolean flag = false;                                                //設(shè)置標(biāo)志位
                    while (size >= 0 && ch == ')' && stack.get(size) != '(') {            //若當(dāng)前ch為右括號(hào),則 棧里元素從棧頂一直彈出,直到彈出到 左括號(hào)
                        queue.add(String.valueOf(stack.remove(size)));                    //注意此處條件:ch并未入棧,所以并未插入隊(duì)列中;同樣直到找到左括號(hào)的時(shí)候,循環(huán)結(jié)束了,所以左括號(hào)也不會(huì)放入隊(duì)列中【也就是:后綴表達(dá)式中不會(huì)出現(xiàn)括號(hào)】
                        size--;                                                            //size-- 保證下標(biāo)永遠(yuǎn)在棧最后一個(gè)元素【棧中概念:指針永遠(yuǎn)指在棧頂元素】
                        flag = true;                                                    //設(shè)置標(biāo)志位為true  表明一直在?。ǎ┲械脑?
                    }
                    while (size >= 0 && !flag && basic.get(stack.get(size)) >= basic.get(ch)) {    //若取得不是()內(nèi)的元素,并且當(dāng)前棧頂元素的優(yōu)先級(jí)>=對(duì)比元素 那就出棧插入隊(duì)列
                        queue.add(String.valueOf(stack.remove(size)));                    //同樣  此處也是remove()方法,既能得到要獲取的元素,也能將棧中元素移除掉
                        size--;
                    }
                }
                if (ch != ')') {                                                            //若當(dāng)前元素不是右括號(hào)
                    stack.add(ch);                                                        //就要保證這個(gè)符號(hào) 入棧
                } else {                                                                //否則就要出棧 棧內(nèi)符號(hào)
                    stack.remove(stack.size() - 1);
                }
            }
            if (i == charArr.length - 1) {                                                //如果已經(jīng)走到了  中綴表達(dá)式的最后一位
                if (len > 0) {                                                            //如果len>0  就截取數(shù)字
                    queue.add(String.valueOf(Arrays.copyOfRange(charArr, i - len + 1, i + 1)));
                }
                int size = stack.size() - 1;                                            //size表示棧內(nèi)最后一個(gè)元素下標(biāo)
                while (size >= 0) {                                                        //一直將棧內(nèi)  符號(hào)全部出棧 并且加入隊(duì)列中  【最終的后綴表達(dá)式是存放在隊(duì)列中的,而棧內(nèi)最后會(huì)被彈空】
                    queue.add(String.valueOf(stack.remove(size)));
                    size--;
                }
            }

        }
        return queue.stream().collect(Collectors.joining(","));                            //將隊(duì)列中元素以,分割 返回字符串
    }


    /**
     * 將 后綴表達(dá)式 進(jìn)行  運(yùn)算 計(jì)算出結(jié)果
     *
     * @param equation
     * @return
     */
    public String dealEquation(String equation) {
        String[] arr = equation.split(",");                                    //根據(jù), 拆分字符串
        List<String> list = new ArrayList<String>();                            //用于計(jì)算時(shí)  存儲(chǔ)運(yùn)算過(guò)程的集合【例如list中當(dāng)前放置  100   20  5  /  則取出20/5 最終將結(jié)果4存入list   此時(shí)list中結(jié)果為  100  4 】


        for (int i = 0; i < arr.length; i++) {                                    //此處就是上面說(shuō)的運(yùn)算過(guò)程, 因?yàn)閘ist.remove的緣故,所以取出最后一個(gè)數(shù)個(gè)最后兩個(gè)數(shù)  都是size-2
            int size = list.size();
            switch (arr[i]) {
                case "+":
                    double a = Double.parseDouble(list.remove(size - 2)) + Double.parseDouble(list.remove(size - 2));
                    list.add(String.valueOf(a));
                    break;
                case "-":
                    double b = Double.parseDouble(list.remove(size - 2)) - Double.parseDouble(list.remove(size - 2));
                    list.add(String.valueOf(b));
                    break;
                case "*":
                    double c = Double.parseDouble(list.remove(size - 2)) * Double.parseDouble(list.remove(size - 2));
                    list.add(String.valueOf(c));
                    break;
                case "/":
                    double d = Double.parseDouble(list.remove(size - 2)) / Double.parseDouble(list.remove(size - 2));
                    list.add(String.valueOf(d));
                    break;
                default:
                    list.add(arr[i]);
                    break;                                    //如果是數(shù)字  直接放進(jìn)list中
            }
        }
        return list.size() == 1 ? list.get(0) : "運(yùn)算失敗";                    //最終list中僅有一個(gè)結(jié)果,否則就是算錯(cuò)了
    }

    public static void main(String[] args) {
        Calculator calculator = new Calculator();
    }
}

總結(jié) 

到此這篇關(guān)于如何用Java的swing編寫簡(jiǎn)單計(jì)算器的文章就介紹到這了,更多相關(guān)Java簡(jiǎn)單計(jì)算器內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論