Storing and using arithmetic operators

1.1k Views Asked by At

I want to program the following application with JavaFx:

The program generates math tasks which the user has to solve. With check boxes you can decide which operators (+ - * /) will occur. If all 4 options are checked, every operator should be used once. So the output will be something like this:

4+3-2*1/2

My problem is that I have no idea how I can store the selected operators and how I can insert them later on in the program as a working operator and not as a char or string because in the end the program has to compare the users solution with the calculated solution from the computer.

Thank you for your help and suggestions I really hope someone can help me with this.

2

There are 2 best solutions below

2
Bohemian On BEST ANSWER

Define an enum, eg

public enum ArithmeticOperator implements BiFunction<Double, Double, Double>  {
    PLUS("+", (a, b) -> a + b),
    MINUS("-", (a, b) -> a - b),
    MULTIPLY("*", (a, b) -> a * b),
    DIVIDE("/", (a, b) -> a / b);

    private final String symbol;
    private final BiFunction<Double, Double, Double> operation;

    ArithmeticOperator(String symbol, BiFunction<Double, Double, Double> operation) {
        this.symbol = symbol;
        this.operation = operation;
    }

    public Double apply (Double a, Double b) {
        return operation.apply(a, b);
    }

    public String toString() {
        return symbol;
    }
}

You can verify using by examining ArithmeticOperator.values().

1
Yacino On

You can store the operators using String or Chars, then just use switch statements to define which operator, or even If Else.

there is a such project but it's developped using C#, just to gut idea.

https://www.codeproject.com/Articles/88435/Simple-Guide-to-Mathematical-Expression-Parsing