存储和使用算术运算符

Storing and using arithmetic operators

我想用 JavaFx 编写以下应用程序:

程序生成用户必须解决的数学任务。使用复选框,您可以决定将出现哪些运算符 (+ - * /)。如果选中所有 4 个选项,则每个运算符都应使用一次。所以输出将是这样的:

4+3-2*1/2

我的问题是我不知道如何存储选定的运算符以及如何稍后将它们作为工作运算符而不是作为字符或字符串插入到程序中,因为最终程序必须将用户的解决方案与计算机计算的解决方案进行比较。

感谢您的帮助和建议我真的希望有人能帮助我。

您可以使用 String 或 Chars 存储运算符,然后只需使用 switch 语句定义哪个运算符,甚至 If Else.

有一个这样的项目,但它是使用 C# 开发的,只是凭直觉。

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

定义一个enum,例如

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;
    }
}

您可以通过检查 ArithmeticOperator.values() 来验证使用情况。