-2

I want to be able to use a set of variables that can stand in for mathematical operators. I am attempting to create a calculator as a learning exercise. I figure it would not be good to have the calculation occur every time a button is pressed, so how do I change the operators in a question without containing the calculations in an if statement?

Example

string plus = +;
string equals = =;
public void button_clicked(....)
{
    .....
    7 equals 4 plus 3;
Community
  • 1
  • 1

1 Answers1

1

First question. Why would it not be good to calculate when the button is pressed, much simpler.

If you really want you can use a command pattern and store a list of commands to execute when the user clicks equals.

E.g.

public interface Operation {

    public double execute();

}

public class Add implements Operation {

    private double num1;
    private double num2;

    public Add(double num1, double num2) {
        this.num1 = num1;
        this.num2 = num2;
    }

    public double execute() {
        return num1 + num2;
    }

}

Then each time a button is peressed, you create a new operation and store in list. When equals is pressed you execute each operation passing the result from one to the next.

You will obviously need many more operations.

cowls
  • 24,013
  • 8
  • 48
  • 78