Answer the question
In order to leave comments, you need to log in
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
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.
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 questionAsk a Question
731 491 924 answers to any question