Implement a simple calculator in Java

Implement a simple calculator in Java

​ This calculator implements the simplest four arithmetic operations, with a simple interface, and friends can make modifications on this basis according to their needs, with strong scalability

Effect picture:

Insert picture description here

Code:

public class Counter extends JPanel {
    
    
    public Graphics g = null;

    public static void main(String[] args) {
    
    
        Counter counter = new Counter();
        counter.run();
    }

    public void run() {
    
    
        CouterListener couterListener = new CouterListener();
        // 窗体标题
        JFrame frame = new JFrame("Calculate");
        // 布局:上下左右的间距为10
        FlowLayout fl = new FlowLayout(FlowLayout.CENTER, 10, 10);
        frame.setLayout(fl);
        // 界面的的尺寸
        frame.setSize(270, 400);
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(3);
        // 固定窗体的大小,无法通过鼠标改变大小
        frame.setResizable(false);

        // 多行文本框
        JTextArea field = new JTextArea();
        // 文本框的尺寸
        field.setPreferredSize(new Dimension(250, 50));

        // 设置最外层Frame的行数为2,一行放文本框,一行放按钮
        field.setRows(3);
        frame.add(field);
        // 背景颜色(可根据自己要求进行修改)
        frame.setBackground(Color.GRAY);
        couterListener.setJText(field);
        // 按钮布局,可以根据需要进行修改
        String BtArray[] = {
    
     "1", "2", "3", "+",
                             "4", "5", "6", "-",
                             "7", "8", "9", "*",
                             ".", "0", "=", "/" };

        // 按钮一共4行4列
        this.setLayout(new GridLayout(4, 4, 10, 10));
        frame.add(this);
        for (int i = 0; i < 16; i++) {
    
    
            JButton button = new JButton(BtArray[i]);
            // 按钮的颜色
            button.setForeground(Color.DARK_GRAY);
            button.setPreferredSize(new Dimension(50, 50));
            button.setContentAreaFilled(false);
            this.add(button);
            // 给按钮绑定点击事件
            button.addActionListener(couterListener);
        }
        //添加CE按钮
        JButton ce = new JButton("CE");
        ce.setForeground(Color.DARK_GRAY);
        ce.setPreferredSize(new Dimension(250, 50));
        ce.setContentAreaFilled(false);
        ce.addActionListener(couterListener);
        frame.add(ce);

        // 使窗口显示
        frame.setVisible(true);
        g = frame.getGraphics();
    }
}

/**
 * 这是监听类
 *
 * 过程解析
 * 以 5 + 3 = 8为例:
 * 当输入5的时候 temp = 5 (temp用于接收最新输入的数据)
 * 当输入+的时候 result = temp,也就是说result = 5 (result用于输出结果)
 *             count = “+”  (count会保存最近的运算符)
 * 当输入8的时候 temp = 8 (temp用于接收最新输入的数据)
 * 当输入=的时候 输出结果是 [result count temp]的结果,也就是 5 + 8的运算结果
 */
class CouterListener implements ActionListener {
    
    
    // 文本域对象
    private JTextArea JF;
    public int x = 0;
    //记录最新输入的是否为数字
    public boolean isNumber = true;
    // 结果
    public Double resulte = 0.0, temp = 0.0;
    public String num[] = new String[3];
    // 用于保存等号之前一次的运算符,比如 + - * /
    public String count;

    // 设置文本域
    public void setJText(JTextArea F) {
    
    
        JF = F;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
    
    
        // 运算符事件:+ - * / 运算符
        ArrayList calculateCommands = new ArrayList<String>();
        calculateCommands.add("+");
        calculateCommands.add("-");
        calculateCommands.add("*");
        calculateCommands.add("/");
        // 获得当前的命令
        String command = e.getActionCommand();
        if ("CE".equals(command)) {
    
    
            // 归零
            resulte = temp = 0.0;
            count = "";
            JF.setText("");
            isNumber = true;
        }else if (calculateCommands.contains(command)) {
    
    
            // + - * /
            JF.setText(JF.getText() + command + "\n");
            if (isNumber) {
    
    
                //输入运算符时,result保存运算符之前的数
                resulte = temp;
            }
            // 保存本次的运算符
            count = e.getActionCommand();
            isNumber = false;
        } else if ("=".equals(command)) {
    
    
            // 计算结果
            if ("+".equals(count)) {
    
    
                resulte = resulte + temp;
                JF.setText(resulte + "");
            } else if ("-".equals(count)) {
    
    
                resulte = resulte - temp;
                JF.setText(resulte + "");
            } else if ("*".equals(count)) {
    
    
                resulte = resulte * temp;
                JF.setText(resulte + "");
            } else if ("/".equals(count)) {
    
    
                resulte = resulte / temp;
                JF.setText(resulte + "");
            }
        } else {
    
    
            //输入的不是 ce + - * / = 的时候,即输入的是数字的时候
            JF.setText(JF.getText() + command);
            if (!isNumber) {
    
    
                //如果上一次输入的是字符
                //正则表达式:根据换行符[\n]将文本框内字符串变成字符串数组
                num = JF.getText().split("\\n");
                //将运算符后面的(即换行符后面的)数字保存到temp中去
                temp = Double.parseDouble(num[1]);

                // 将下面注释打开就可以知道num和temp的作用了
                System.out.println("num: ");
                for (int i = 0; i < num.length; i++) {
    
    
                    System.out.printf("[" + i + "]:\"" +num[i] + "\"\n");
                }
                System.out.println("temp: " + temp);
            } else {
    
    
                //如果是第一次输入数字
                temp = Double.parseDouble(JF.getText());
            }
        }
    }
}

Guess you like

Origin blog.csdn.net/weixin_44829930/article/details/111780377
Recommended