1

创建一个模拟一个非常简单的计算器的程序

所以我被要求实现一个代表二进制(有2个参数)算术表达式的抽象类

abstract class ArithmeticExpression {

    double binary1;
    double binary2;

    public abstract void evaluate ();

    public abstract void display ();

}

所以我创建了子类加、乘、减和除。在减去我有:

public class subtract extends ArithmeticExpression {
    // private double result;
    double binary1;
    double binary2;

    public subtract (double x, double y) {
        this.binary1 = x;
        this.binary2 = y;
    }

    public  void evaluate () {

        System.out.println("Expression: " + getsubX() + " - " + getsubY() + " = ");

        // return result;
    }

    public  void display () {

    }

    public double getsubX() {

    }

    public double getsubY() {

    }

使用这些类,我应该能够表示任意表达式,而无需硬编码。

也有人说评估应该以双精度返回结果,而显示方法应该以字符串形式打印表达式。我在正确的轨道上吗?我在这里想念什么?我不明白它是如何能够代表任何表达的部分?

4

2 回答 2

0

Using your abstract ArithmeticExpression, here's what the Subtract class should look like. Java classes start with a capital letter.

public class Subtract extends ArithmeticExpression {
    double  result;

    public Subtract(double x, double y) {
        this.binary1 = x;
        this.binary2 = y;
    }

    @Override
    public void evaluate() {
        result = binary1 - binary2;
    }

    @Override
    public void display() {
        System.out.println("Expression: " + binary1 + 
                " - " + binary2 + " = " + result);
    }

}

You don't have to re-declare binary1 and binary2. They are instantiated in the abstract ArithmeticExpression class.

You do have to provide a double for the result. This should have been done in the abstract ArithmeticExpression class.

The evaluate() method is for evaluation.

The display() method is for display.

You don't have to define any other methods in your Subtract concrete class.

于 2013-11-13T18:52:37.807 回答
0

如果您想评估以以下形式插入的任何表达式

4 + 3 * ( 4 + 5)

您需要创建二叉树或堆栈并填充这些值和运算符。

我很不明白的是你所谓的二进制表示为双。如果你想要二进制计算,你应该使用 unsigned int 或 long (或任何其他类型,不是浮点数)

于 2013-11-13T18:51:17.277 回答