【问题标题】:Calculator with batches of operations in javajava中批量运算的计算器
【发布时间】:2023-03-26 14:36:01
【问题描述】:

需要做一个批处理的java计算器。它必须接受一个操作,然后,对于下一个操作,只需使用前一个操作的结果作为其新操作的第一个值。

    public class Calculator {
/**
* Public constructor of the calculator.
*/

    **public Calculator () {/*...*/}**
 
/**
* Clean the internal state of the calculator
*/

    **public void cleanOperations () { /*...*/ }**

/**
* Add a new operation to the internal state of the calculator.
* It is worth mentioning that the calculator behaves in an accumulative way ,
* thus only first operation has two operands.
* The rest of computations work with the accumulated value and only an extra
* new operand. Second input value must be ignored if the operation does not
* correspond to the first one.
*
* @param operation operation to add , as string , "+", "-", "*", "/".
* @param values Operands of the new operation (one or two operands ).
* Uses the varargs feature.
* https :// docs.oracle.com/javase /8/ docs/technotes/guides/language/varargs.html
* @throws IllegalArgumentException If the operation does not exist.
*/

    **public void addOperation(String operation , float ... values) { /*...*/ }**
/**

* Execute the set of operations of the internal state of the calculator.
* Once execution is finished , internal state (operands and operations)
* is restored (EVEN if exception occurs ).
* This calculator works with "Batches" of operations.
* @return result of the execution
* @throws ArithmeticException If the operation returns an invalid value
* (division by zero)
*/

    **public float executeOperations () { /*...*/ }**

/**
* Current internal state of calculator is printed
* FORMAT:
* "[{+/ -/"/"/*}] value1_value2 [{+/ -/"/"/*}] value1 [{+/ -/"/"/*}] value1 {...}"
* @return String of the internal state of the calculator
*/
@Override
public String toString () { /* ... */ }
}

应该通过一些测试:

// Add operations, calculate internal state representation (string pattern) and execute them as a single batch
    calculator.addOperation("+", 4.5f, 6.8f);
    calculator.addOperation("-", 3.1f);
    calculator.addOperation("/", 6f);
    assertEquals("[STATE:[+]4.5_6.8[-]3.1[/]6.0]", calculator.toString());
    result = calculator.executeOperations();
    assertEquals("[STATE:]", calculator.toString()); // state is restored
    assertEquals(1.366f, result, EPSILON);//EPSILON = 0.01f

如您所见,它必须通过使用 2 个值执行第一个操作,但下一个操作使用前一个值存储的值,然后使用运算符和值执行新操作。

【问题讨论】:

    标签: java string constructor calculator


    【解决方案1】:

    你在找这个吗?

    public class Calculator {
    
        private String operation;
        private float[] values;
        private float answer;
    
        /**
         * Public constructor of the calculator.
         */
        public Calculator() {
    
        }
    
        /**
         * Clean the internal state of the calculator
         */
        public void cleanOperations() {
             operation = null;
             values = null;
             answer = 0;
        }
    
        /**
         * Add a new operation to the internal state of the calculator.
         * It is worth mentioning that the calculator behaves in an accumulative way ,
         * thus only first operation has two operands.
         * The rest of computations work with the accumulated value and only an extra
         * new operand. Second input value must be ignored if the operation does not
         * correspond to the first one.
         *
         * @param operation operation to add , as string , "+", "-", "*", "/".
         * @param values    Operands of the new operation (one or two operands ).
         *                  Uses the varargs feature.
         *                  https :// docs.oracle.com/javase /8/ docs/technotes/guides/language/varargs.html
         * @throws IllegalArgumentException If the operation does not exist.
         */
        public void addOperation(String operation, float... values) {
            if (!(operation.equals("+") || operation.equals("-") || operation.equals("*") || operation.equals("/"))) {
                throw new IllegalArgumentException(operation + " is not a valid operator. ( '+', '-', '*', '/')");
            }
            this.operation = operation;
            this.values = values;
        }
    
        /**
         * Execute the set of operations of the internal state of the calculator.
         * Once execution is finished , internal state (operands and operations)
         * is restored (EVEN if exception occurs ).
         * This calculator works with "Batches" of operations.
         *
         * @return result of the execution
         * @throws ArithmeticException If the operation returns an invalid value
         *                             (division by zero)
         */
        public float executeOperations() {
            switch (operation) {
                case "+":
                    if (values.length == 1) {
                        answer += values[0];
                    } else {
                        for (float value : values) {
                            answer += value;
                        }
                    }
                    break;
                case "-":
                    if (values.length == 1) {
                        answer -= values[0];
                    } else if (values.length != 0) {
                        answer = values[0];
                        for (int i = 1; i < values.length; i++) {
                            answer -= values[i];
                        }
                    }
                    break;
                case "*":
                    if (values.length == 1) {
                        answer *= values[0];
                    } else if (values.length != 0) {
                        answer = values[0];
                        for (int i = 1; i < values.length; i++) {
                            answer *= values[i];
                        }
                    }
                    break;
                case "/":
                    if (values.length == 1) {
                        if (values[0] == 0) {
                            throw new ArithmeticException("Can not divide " + answer + " with " + values[0]);
                        }
                        answer /= values[0];
                    } else if (values.length != 0) {
                        answer = values[0];
                        for (int i = 1; i < values.length; i++) {
                            if (values[i] == 0) {
                                throw new ArithmeticException("Can not divide " + answer + " with " + values[i]);
                            }
                            answer /= values[i];
                        }
                    }
                    break;
            }
            return answer;
        }
    
        /**
         * Current internal state of calculator is printed
         * FORMAT:
         * "[{+/ -/"/"/*}] value1_value2 [{+/ -/"/"/*}] value1 [{+/ -/"/"/*}] value1 {...}"
         *
         * @return String of the internal state of the calculator
         */
        @Override
        public String toString() {
            StringBuilder string = new StringBuilder("values: [");
            for (float value: values) {
                string.append(value)
                        .append(" ")
                        .append(operation)
                        .append(" ");
            }
            string.append("] answer = ").append(answer);
            return string.toString();
        }
    }
    

    【讨论】:

    • 我用它应该通过的一些测试更新了代码,因为使用该代码,例如在 executeOperations 中,我认为我没有很好地解释它是如何工作的。谢谢!
    • @DanielRodriguez 好的
    • 你能告诉我我应该修改什么以通过问题底部的测试吗?提前谢谢你
    • @DanielRodriguez 您将需要创建使用单个操作数执行的操作的日志创建一个 String 对象并将这些详细信息记录到用户执行的操作中。toString() 您应该从该方法返回该对象并重置当用户传递两个操作数并且当用户调用执行操作时它也可以
    猜你喜欢
    • 2023-01-11
    • 1970-01-01
    • 2012-11-27
    • 2015-09-28
    • 2021-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-28
    相关资源
    最近更新 更多