0

my super class(abstract):

  • exp1.display will display my result
  • exp1.evaluate should return ((1.2 * 4.2) + 4.2)) but it returns only (5.04 + 4.2)

I need

  • help with my evaluate method and
  • a test class but to test and see if the operations from my subclasses are working but im not sure how to do it.

.

abstract class arithmeticexpression {
    public Double a;

    public Double b;

    arithmeticexpression(Double a, Double b)
    {
        this.a = a;
        this.b = b;
    }

    public void display()
    {

    }

    public double evaluation()
    {

    }
}

public class addition extends arithmeticexpression {
    Double x;

    Double y;

    public addition(Double a, Double b)
    {
        super(a, b);
    }

    public void evaluation()
    {

        System.out.println(a + " + " + b);
    }

    public Double display()
    {
        return a + b;
    }

}

// subclass of arithmeticexpression
public class multiplication extends arithmeticexpression {

    public multiplication(Double a, Double b)
    {
        super(a, b);
    }

    public void evaluation()
    {
        System.out.println(a + " * " + b);
    }

    public Double display()
    {
        return a * b;
    }

}

My main:

  import java.util.Scanner;

  public class main {
   public static void main(String[] args) {
    arithmetic exp1 = new addition(new multiplication(1.2,4.2).display(), 4.2);
    exp1.display();
    exp1.evaluation();
       }
  }
user2946804
  • 27
  • 1
  • 4

2 Answers2

4

At the moment, both of your classes only accept doubles as arguments of their constructor. So they only accept values. A double can't contain an expression like (2 * 1.2). It can only contain a double value: 2.4. So, your arithmetic expression classes should also accept other arithmetic expressions as argument.

And you should probably introduce an additional subclass of ArithmeticExpression which only wraps a value.

Once that is done, you'll be able to have

ArithmeticExpression e = 
     new Addition(new Multiplication(new Literal(1.2), new Literal(4.2)),
                  new Literal(4.2));
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
0

Your expression needs to be able to reuse child expressions, not just their value. So introduce a 'dyadicexpression' which contains two sub-expressions iso two values, as in:

abstract class ArithmeticExpression {
   public Double evaluation(){ return 0.0 }; 
   public String display(){ return ""};
}
class ConstantValue extends ArithmeticExpression
{
  private double value;
  ...
}
abstract class DyadicExpression extends ArithmeticExpression
{
   private ArithmeticExpression a;
   private ArithmeticExpression b;
}
class Addition extends DyadicExpression {
   public String display() {    
     return a.display() + " + " + b.display();  
  }


  public Double evaluation() {
     return a.evaluation() + b.evaluation(); 
  }
}

In your main() do System.out.println(expr.display());

GeertPt
  • 16,398
  • 2
  • 37
  • 61