计算器——Java实现

目录

前言

实验要求:

​编辑 界面效果:

 实现计算器类与方法:


前言

为完成数据结构实训课作业,而写的计算器。

实验要求:

 界面效果:

 实现计算器类与方法:

该计算器主要由三大类实现:Calculator,Calculate,以及Stack(老师要求自己写一个数据结构类型(我使用是链式存储));

Calculator类:我主要实现了界面的组件的定义,组合,以及添加事件监听器,以及AC,BaskSpace0,1,2等实现相关组件功能的实现。

代码实现:

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Calculator {
    //定义基本组件
    JFrame frame=new JFrame("计算器");
    JPanel p1=new JPanel();
    JPanel p2=new JPanel();
    JPanel p3=new JPanel();
    TextArea ta=new TextArea(3,40);
    TextArea showTa=new TextArea("历史记录\n",14,20);
    //组装组件,并添加对应方法
    public void init() {
        //添加组件
        p1.add(ta);
        p3.add(showTa);

        p2.setLayout(new GridLayout(5,4,4,4));
        ActionListener actionListener=new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String command=e.getActionCommand();
                ta.append(command);
            }
        };
        p2.add(new JButton(new AbstractAction("AC") {
            @Override
            public void actionPerformed(ActionEvent e) {
                ta.setText("");
            }
        }));//清空(计算器显示屏中的内容)
        p2.add(new JButton(new AbstractAction("BackSpace") {
            @Override
            public void actionPerformed(ActionEvent e) {
                String s=ta.getText();
                //如果ta中字符串长度不为0,则可以进行回撤;
                if(s.length()!=0){
                    ta.setText(s.substring(0,s.length()-1));
                }
            }
        }));
        p2.add(actionBtn(new JButton("("),actionListener));
        p2.add(actionBtn(new JButton(")"),actionListener));

        for (int i = 7; i < 10; i++) {
            p2.add(actionBtn(new JButton(i+""),actionListener));
        }
        p2.add(actionBtn(new JButton("+"),actionListener));

        for(int i=4;i<=6;i++){
            p2.add(actionBtn(new JButton(i+""),actionListener));
        }
        p2.add(actionBtn(new JButton("-"),actionListener));

        for (int i=1;i<=3;i++){
            p2.add(actionBtn(new JButton(""+i),actionListener));
        }
        p2.add(actionBtn(new JButton("x"),actionListener));
        p2.add(actionBtn(new JButton("."),actionListener));

        p2.add(actionBtn(new JButton("0"),actionListener));
        p2.add(actionBtn(new JButton("/"),actionListener));
        JButton btn_equal=new JButton(new AbstractAction("=") {
            @Override
            public void actionPerformed(ActionEvent e) {
                String s=ta.getText();
                Calculate calculate=new Calculate();
                String result=calculate.evaluate(s);
                showTa.append(s+"="+result+"\n");
                ta.setText(result);

            }
        });
        //窗口内组件布局的设置
        p2.add(btn_equal);
        Box left_box=Box.createVerticalBox();
        left_box.add(p1);
        left_box.add(p2);
        Box box=Box.createHorizontalBox();
        box.add(left_box);
        box.add(p3);
        frame.add(box);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//关闭计算器窗口
        frame.pack();//设置窗口合适的大小
        frame.setVisible(true);//显示窗口

    }
    public static void main(String[] args) {
        // TODO 自动生成的方法存根
        //调用init()方法
        new Calculator().init();

    }
    //给按钮添加事件监听器
    public JButton actionBtn(JButton btn,ActionListener actionListener){
        btn.addActionListener(actionListener);
        return btn;
    }

}

Calculate类:本类也是代码最核心的地方,主要实现本项目最核心的部分,里面包含很多逻辑关系,利用栈的思想,实现计算器+,-,x,/,=,以及带有小数点,负数,与()(括号)等实现。代码中有很多值得被考虑:如:优先级问题,除法分母不为0等问题。都值得大家慢慢体会!!

代码实现: 

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
//import java.util.Stack;
public class Calculate {

    public String evaluate(String express) {
        String expression = express;
        double calculate = 0;
        try {
            List<String> infixExpression = depositList(expression);//中缀表达式
            List<String> calculateExpression = parsExpression(infixExpression);//后缀表达式
            calculate = calculate(calculateExpression);
        }catch (RuntimeException e){
            return "error";
        }
        if (calculate==0){
            return "0";
        } else {
            BigDecimal bigDecimal = new BigDecimal(String.format("%.12f",calculate));//去掉前面多余的零
            String result = bigDecimal.toString();
            if(result.indexOf(".")>0){
                result = result.replaceAll("0+?$","");//去掉后面无用的零
                result = result.replaceAll("[.]$","");//如小数点后面全是零去掉小数点
            }
            return result;
        }
    }


    public static List<String> parsExpression(List<String> list) {//方法:将得到的中缀表达式对应的转换后缀表达式对应的List
        //定义两个栈
        Stack<String> s1 = new Stack<String>(); // 符号栈
        List<String> s2 = new ArrayList<String>(); // 储存中间结果的Lists2


        for(String item: list ) {
            if(item.matches("^[1-9]\\d*\\.\\d*|0\\.\\d*[1-9]\\d*|[1-9]\\d*|0|-[1-9]\\d*\\.\\d*|-0\\.\\d*|-[1-9]\\d*$")) {//如果是一个数加入s2
                s2.add(item);
            } else if (item.equals("(")) {
                s1.push(item);
            } else if (item.equals(")")) {

                while(!s1.peek().equals("(")) {//如果是右括号“)”,则依次弹出s1栈顶的运算符,并压入s2,直到遇到左括号为止,此时将这一对括号丢弃
                    s2.add(s1.pop());
                }
                s1.pop();//将 ( 弹出 s1栈, 消除小括号
            } else {
                while(s1.size() != 0 && operation.getValue(s1.peek()) >= operation.getValue(item) ) {
                    s2.add(s1.pop());
                }

                s1.push(item);
            }
        }


        while(s1.size() != 0) {	//将s1中剩余的运算符依次弹出并加入s2
            s2.add(s1.pop());
        }

        return s2;

    }

    public static List<String> depositList(String s) {

        List<String> list = new ArrayList<String>();//定义一个List,存放中缀表达式 对应的内容
        int i = 0;
        String str;
        char c;
        do {
            boolean isMinus = false;
            if ((c=s.charAt(i))=='-'){
                if (i==0 || s.charAt(i-1)=='('){
                    isMinus=true;
                }
            }
            if(((c=s.charAt(i)) < 48 ||  (c=s.charAt(i)) > 57) && !isMinus) {
                list.add("" + c);
                i++;
            } else {
                str = ""; //先将str 置成"" '0'[48]->'9'[57]
                do {
                    str += c;
                    i++;
                }while(i < s.length() && (((c=s.charAt(i)) >= 48 && (c=s.charAt(i)) <= 57) || (c=s.charAt(i)) == '.'));
                list.add(str);
            }
        }while(i < s.length());
        return list;
    }

    public static double calculate(List<String> list) {
        Stack<String> stack = new Stack<String>();// 创建栈
        for (String item : list) {
            if (item.matches("^[1-9]\\d*\\.\\d*|0\\.\\d*[1-9]\\d*|[1-9]\\d*|0|-[1-9]\\d*\\.\\d*|-0\\.\\d*|-[1-9]\\d*$")) { //使用正则表达式匹配多位数
                stack.push(item);
            } else {
                double num2 = Double.parseDouble(stack.pop());	// pop出两个数,并运算, 再入栈,如果空就赋值为零是为了让负数也能算
                double num1 = Double.parseDouble(stack.pop());
                double res = 0;
                if (item.equals("+")) {
                    res = num1 + num2;
                } else if (item.equals("-")) {
                    res = num1 - num2;
                } else if (item.equals("x")) {
                    res = num1 * num2;
                } else if (item.equals("/")&&num2!=0) {
                    res = num1 / num2;
                } else {
                    throw new RuntimeException("运算符有误");
                }

                stack.push("" + res);
            }

        }

        return Double.parseDouble(stack.pop());
    }

}
//编写一个类 Operation 可以返回一个运算符 对应的优先级
class operation {
    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 "x":
                result = Mul;
                break;
            case "/":
                result = Div;
                break;
            default:

                break;
        }
        return result;
    }

}

 Stack类:该类是最底层的东西,主要通过结点链式存储方法写出的类,该类在Java.util包下就已经有该方法的实现,但在这我本人是为了完成老师的要求,才加上去的。

代码实现:

public class Stack<T>  {
    //记录首结点
    private Node head;
    //栈中元素的个数
    private int N;

    public Stack() {
        head = new Node(null, null);
        N = 0;
    }

    //判断当前栈中元素个数是否为0
    public boolean isEmpty() {
        return N == 0;
    }

    //把t元素压入栈
    public void push(T t) {
        Node oldNext = head.next;
        Node node = new Node(t, oldNext);
        head.next = node;
//个数+1
        N++;
    }

    //弹出栈顶元素
    public T pop() {
        Node oldNext = head.next;
        if (oldNext == null) {
            return null;
        }
//删除首个元素
        head.next = head.next.next;
//个数-1
        N--;
        return oldNext.item;
    }
    public T peek(){
        if(!isEmpty()){
            return head.next.item;
        }
        return null;
    }

    //获取栈中元素的个数
    public int size() {
        return N;
    }

    private class Node {
        public T item;
        public Node next;

        public Node(T item, Node next) {
            this.item = item;
            this.next = next;
        }
    }
}

这篇文章到这也达到尾声了,谢谢大家阅览!最后也希望大家能够试试这计算器的功能,帮我检验它是否存在bug,如果有的话,请留言,我看到之后就一定修改。

冬天到了,春天还会远吗?

  • 5
    点赞
  • 49
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 5
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Luck&Strive

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值