P
P
Pavel Subbotin2020-12-13 13:09:08
Java
Pavel Subbotin, 2020-12-13 13:09:08

How to make a multi-action calculator in Java?

Guys, how to make a calculator that has several actions and where the multiplication / division is performed first, and the addition / subtraction is the second. In the classroom, we wrote such code, but is it possible to somehow adjust it for several actions?

JButton btn;
    JLabel label;
    static JButton lastBtn;

    static double ch1;
    static double ch2;
    double result;

    public Operation(JButton btn, JLabel label) {
        this.btn = btn;
        this.label = label;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        ch2 = Double.valueOf(label.getText());
        switch(btn.getText()){
            case "+":
            case "-":
            case "/":
            case "*":
                lastBtn = btn;
                ch1 = ch2;
                label.setText("0");
                break;
            case "=":
                if(ch2 == 0 && lastBtn.getText().equals("/")){
                    label.setText("На 0 не /");
                }else{
                    switch (lastBtn.getText()){
                        case "+":
                            result = ch1 + ch2;
                            break;
                        case "-":
                            result = ch1-ch2;
                            break;
                        case "*":
                            result = ch1*ch2;
                            break;
                        case "/":
                            result = ch1/ch2;
                            break;
                    }

                    if (result%1 == 0)label.setText(String.valueOf((int)result));
                    else label.setText(String.valueOf(result));
                }
                break;
        }
    }

Answer the question

In order to leave comments, you need to log in

2 answer(s)
O
Orkhan, 2020-12-13
Hasanly @azerphoenix

Hello!


I meant how to adjust the code that I did in class so that you can do several things and follow all the rules, such as that multiplication / division comes first, and then addition / subtraction comes.

Here the important point is the following, summation or subtraction can be framed in parentheses and, accordingly, you will need to perform them before multiplication or division.
As for me, it is necessary to accept the string with the expression completely, and then parse it. Find brackets in it and execute their contents, and then other operations

D
Denis Zagaevsky, 2020-12-13
@zagayevskiy

You need to take a string, parse it, and execute it.
Key phrases for searching:
Reverse Polish notation.
sorting yard algorithm.
Recursive descent algorithm.
You can’t make anything out of the code that you have, because there is nothing in it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question