Java实现简易计算器(逆波兰表达式)

本文介绍了如何利用JavaSwing库和栈数据结构,将用户输入的中缀表达式转换为后缀表达式(逆波兰表达式),并进行计算。通过解析操作符优先级和栈操作,实现了简单的计算器功能。
摘要由CSDN通过智能技术生成

内容

利用逆波兰表达式和JavaSwing库,以及栈

 思路

1.将输入的字符串先用List集合表示

2.在用一个Lisl和栈的转换为后缀表达式

3.最后计算后缀表达式(逆波兰表达式)

代码实现 

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;


public class EasyCalculator {
    public static void main(String[] args) {
        new WindowInterface();
    }
}

class WindowInterface extends JFrame {
    private JTextField inputField;
    private JButton calculateButton;
    private JTextField result;

    public WindowInterface() {
        setTitle("简易计算器");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(400, 125);
        setResizable(false);

        JPanel panel = new JPanel();
        panel.setLayout(new FlowLayout());

        setLocation(600, 350);

        JLabel inputLabel = new JLabel("输入表达式: ");
        panel.add(inputLabel);

        inputField = new JTextField(24);
        panel.add(inputField);

        calculateButton = new JButton("计算");
         //calculateButton.addActionListener(new CalculateButtonListener());
        panel.add(calculateButton);

        JLabel outLabel = new JLabel("结果: ");
        panel.add(outLabel);

        result = new JTextField(10);
        panel.add(result);

        add(panel);
        setVisible(true);

        calculateButton.addActionListener(new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String str = inputField.getText();
                result.setText(String.valueOf(calculate(parseSuffixExpressionList(toInfixExpressionList(str)))));
            }
        });

    }

    //将得到的List转换为对应的List
    public static java.util.List<String> parseSuffixExpressionList(java.util.List<String> ls) {
        Stack<String> s1 = new Stack<String>();
        java.util.List<String> s2 = new ArrayList<String>();
        //遍历ls
        for (String item : ls) {
            //如果是一个数,加入s2
            if (item.matches("\\d+")) {
                s2.add(item);
            } else if (item.equals("(")) {
                s1.push(item);
            } else if (item.equals(")")) {
                while (!s1.peek().equals("(")) {
                    s2.add(s1.pop());
                }
                s1.pop();//消除( 括号
            } else {
                //当item的优先级小于等于s1栈顶的优先级,将s1弹出压入s2中
                while(s1.size() != 0 && Opera.getValue(s1.peek()) >= Opera.getValue(item)){
                    s2.add(s1.pop());
                }
                s1.push(item);
            }
        }

        //将s1剩余的运算符加入s2
        while (s1.size()!=0){
            s2.add(s1.pop());
        }
        return s2;
    }
    //将中缀表达式转换成对应的List
    public static java.util.List<String> toInfixExpressionList(String s) {
        //定义一个list
        java.util.List<String> ls = new ArrayList<String>();
        int i = 0;//指针
        String str;//对多位数的拼接
        char c;//遍历的每一个字符就放到c
        do {
            if ((c = s.charAt(i)) < 48 || (c = s.charAt(i)) > 57) {
                ls.add("" + c);
                i++;
            } else {
                str = "";
                while (i < s.length() && (c = s.charAt(i)) >= 48 && (c = s.charAt(i)) <= 57){
                    str += c;
                    i++;
                }
                ls.add(str);
            }
        } while (i < s.length());
        return ls;
    }

    //放入ArrayList
    public static java.util.List<String> getListString(String suffixExpression) {
        String[] split = suffixExpression.split(" ");
        java.util.List<String> list = new ArrayList<String>();
        for (String ele : split) {
            list.add(ele);
        }
        return list;
    }

    public static int calculate(List<String> ls) {
        //创建栈
        Stack<String> stack = new Stack<String>();
        //遍历list
        for (String item : ls) {
            if (item.matches("\\d+")) {//匹配的是多位数
                stack.push(item);
            } else {
                int num2 = Integer.parseInt(stack.pop());
                int num1 = Integer.parseInt(stack.pop());
                int res = 0;
                if (item.equals("+")) {
                    res = num1 + num2;
                } else if (item.equals("-")) {
                    res = num1 - num2;
                } else if (item.equals("*")) {
                    res = num1 * num2;
                } else if (item.equals("/")) {
                    if (num2 == 0)
                        throw new RuntimeException("被除数不能为零");
                    res = num1 / num2;
                } else {
                    throw new RuntimeException("运算符有误");
                }
                //把结果入栈
                stack.push("" + res);
            }
        }
        return Integer.parseInt(stack.pop());
    }
}
//编写一个类,返回一个运算符对应的优先级
class Opera{
    private  static int ADD = 1;
    private  static int SUB = 1;
    private  static int MUL = 2;
    private  static int DIV = 2;
    public static int getValue(String operation){
        int result = 0;
        switch (operation){
            case "+":result = ADD;break;
            case "-":result = SUB;break;
            case "*":result = MUL;break;
            case "/":result = DIV;break;
        }
        return result;
    }
}

运行画面 

  • 8
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值