0

I have to write a class in Java that supports representing arithmetic expressions with 2 methods- eval and toString with the following black-box use:

Expression e = 
new Multiplication( 
    new Addition( 
        new Double(2.5), 
        new Double(3.5)), 
    new UnaryMinus( 
        new Integer(5))); 
System.out.println(e.eval());   // should print out -30.0 
System.out.println(e.toString());   // should print out ((2.5 + 3.5) * (-(5))) 

How can I design such class? Which tools? Which Design pattern?

4
  • 2
    Which class(es) do you want to design? What have you tried so far? Jan 25, 2013 at 0:55
  • Sounds like a homework to me. Jan 25, 2013 at 0:56
  • Sounds a lot like homework to me, too. Jan 25, 2013 at 1:18
  • So? The problem isn't that it's homework, the problem is that it's "how do I do this?" Instead of "how do I fix this"?
    – Jeff
    Jan 25, 2013 at 1:22

5 Answers 5

2

You just need to implement each operator's toString and eval appropriately. Then, have each call toString or eval on each of their components as needed, before applying their own part.

So Addition.eval() will perform return left.eval() + right.eval();

Similarly, Addition.toString() will perform return "(" + left.toString() + " + " + right.toString() + ")";

In order to achieve this, you'd use an interface with the Composite pattern Rob suggested to build appropriate classes overriding these methods.

2

How can I design such class?

Well there are lots of clues in the black-box example code you've been given.

  • You need an interface (or possibly an abstract class) called Expression that has an eval method. The eval method needs to return some kind of numeric type - Double would be a good choice, but there are other options.

  • You need some expression classes (that implement or extend Expression) such as Multiplication, Addition and UnaryMinus. These need to provide implementations of the eval method. They also need to override the default toString() method to print the expression.

  • The expression classes also need constructors with parameter types that are implied by the example.

There is a little bit out thought required to figure out how to handle both

new Multiplication( 
    new Addition( 
        new Double(2.5), 
        new Double(3.5)), 
    new UnaryMinus( 
        new Integer(5))); 

and

new Multiplication( 
    new Double(2.5), 
    new Double(3.5)); 

... but that's for you to work out. And learn by working it out for yourself. (Or maybe not bother, because strictly speaking it is not essential to implement the example you've shown us.)

Which tools?

None required ... apart from a Java JDK installation (obviously). Use your favourite / recommended Java IDE, or a simple text editor and the JDK command line tools.

Which Design pattern?

None required. Just a bit of "common or garden variety" polymorphism. Regular OO classes and interfaces.

1
  • +1 for addressing the question piece by piece, but leaving room for the OP to learn.
    – Zach Latta
    Jan 25, 2013 at 2:01
2

Hope this helps

setp 1:

public abstract class Expression
{
    public abstract decimal Evaluate();
    public abstract string toString();
}

step 2:

public abstract class ValueNode:Expression
{
    public int intvalue;
    public decimal decvalue;
    public abstract decimal TEvaluate();
    public abstract string TtoString();

    public override decimal Evaluate()
    {
        return TEvaluate();
    }

    public override string toString()
    {
        return TtoString();
    }
}

Step 2.1:

public abstract class OperationNode:Expression
{
   public Expression left;
   public Expression right;
   public override decimal Evaluate()
    {
        return this.EEvaluate();
    }
    public override string toString()
    {
        return this.EtoString();
    }
    public abstract decimal EEvaluate();
    public abstract string EtoString();

}

step 3:

public class UnaryMinus:OperationNode
{
    public UnaryMinus(Expression Left)
     {
        this.left = Left;

    }
    public override decimal EEvaluate()
    {
        return -(this.left.Evaluate());
    }

    public override string EtoString()
    {
        return string.Format("(-({0}))",left.toString()); ;
    }

}

step 4:

public class DecimalClass:ValueNode
{
    public DecimalClass(decimal decimalValue)
    {
        this.decvalue = decimalValue;
    }

    public override decimal TEvaluate()
    {
        return this.decvalue;
    }

    public override string TtoString()
    {
        return this.decvalue.ToString();
    }
}

step 5:

public class Integer : ValueNode
{
    public Integer(int decimalValue)

    {
        this.intvalue = decimalValue;
    }

 public override decimal TEvaluate()

    {
        return this.intvalue;
    }

    public override string TtoString()

    {
        return this.intvalue.ToString();
    }
}

step 6:

public  class Addition:OperationNode
 {

   public Addition(Expression Left, Expression Right)

    {
        this.left = Left;
        this.right = Right;
    }
    public override decimal EEvaluate()
    {
        return left.Evaluate()+ right.Evaluate();
    }
    public override string EtoString()
    {
        return string.Format("({0}+{1})",left.toString(),right.toString()); ;
    }
}

step 7:

public class Multiplication : OperationNode

{
    public Multiplication(Expression Left, Expression Right)
    {
        this.left = Left;
        this.right = Right;
    }
    public override decimal EEvaluate()
    {
        return left.Evaluate()* right.Evaluate();
    }

    public override string EtoString()
    {
        return string.Format("({0}*{1})",left.toString(),right.toString()); ;
    }
}

step 8:

public class Substraction:OperationNode
{
   public Substraction(Expression Left, Expression Right)
    {
        this.left = Left;
        this.right = Right;
    }
    public override decimal EEvaluate()
    {
        return left.Evaluate()- right.Evaluate();
    }

    public override string EtoString()
    {
        return string.Format("({0}-{1})",left.toString(),right.toString()); ;
    }
}

step 9:

public  class Division: OperationNode
{
   public Division(Expression Left, Expression Right)
    {
        this.left = Left;
        this.right = Right;
    }
    public override decimal EEvaluate()
    {
        return left.Evaluate()/ right.Evaluate();
    }

    public override string EtoString()
    {
        return string.Format("({0}/{1})",left.toString(),right.toString()); ;
    }
}

step 10:

class Program
{
    static void Main(string[] args)
    {

        callComposit();
        Console.ReadKey();
    }

    private static void callComposit()
    {
        //Expression ((2.5+3.5)*(-(5)))
        Multiplication multiplication = new Multiplication(new Addition(new DecimalClass(2.5m), new DecimalClass(3.5m)), new UnaryMinus(new Integer(5)));
        Console.WriteLine(string.Format("\r\n Expression {0} resulted in {1}", multiplication.toString(), multiplication.Evaluate()));



        //Expression (5/6)
        Division division = new Division(new Integer(5), new Integer(6));
        Console.WriteLine(string.Format("\r\n Expression {0} resulted in {1}", division.toString(), division.Evaluate()));
        //Expression ((2.5-3.5)*(-(5)))
        Multiplication multiplication2 = new Multiplication(new Substraction(new DecimalClass(2.5m), new DecimalClass(3.5m)), new UnaryMinus(new Integer(5)));
        Console.WriteLine(string.Format("\r\n Expression {0} resulted in {1}", multiplication2.toString(), multiplication2.Evaluate()));
        //Expression ((2.5/3.5)*(-(5)))
        Multiplication multiplication3 = new Multiplication(new Division(new DecimalClass(2.5m), new DecimalClass(3.5m)), new UnaryMinus(new Integer(5)));
        Console.WriteLine(string.Format("\r\n Expression {0} resulted in {1}", multiplication3.toString(), multiplication3.Evaluate()));

        //Expression ((2.5/3.5)*(-(5))* 3.5)
        Multiplication multiplication4 = new Multiplication(new Multiplication(new Division(new DecimalClass(2.5m), new DecimalClass(3.5m)), new UnaryMinus(new Integer(5))), new DecimalClass(3.5m));
        Console.WriteLine(string.Format("\r\n Expression {0} resulted in {1}", multiplication4.toString(), multiplication4.Evaluate()));


        //Expression ( 3.5*(2.5/3.5)*(-(5)))
        Multiplication multiplication5 = new Multiplication(new Multiplication(new DecimalClass(3.5m), new Division(new DecimalClass(2.5m), new DecimalClass(3.5m))), new UnaryMinus(new Integer(5)));
        Console.WriteLine(string.Format("\r\n Expression {0} resulted in {1}", multiplication5.toString(), multiplication5.Evaluate()));

        //Expression ( 3.5*(2.5/3.5)+ 3.5 *(-(5)))
        Multiplication multiplication6 = new Multiplication(new Addition(new Multiplication(new DecimalClass(3.5m), new Division(new DecimalClass(2.5m), new DecimalClass(3.5m))), new DecimalClass(3.5m)), new UnaryMinus(new Integer(5)));
        Console.WriteLine(string.Format("\r\n Expression {0} resulted in {1}", multiplication6.toString(), multiplication6.Evaluate()));
    }
}

Please comment if anything need to be done to do more better than this way Happy coding

1

If you are allowed to modify the black box usage a little a builder pattern could be a nice approach. It may look something more like :

Builder builder = new MathBuilder(); Expression e = builder.add(new Double(2.5)).add(new Double(3.5).multiply(-5);

You'd have to work out the details around order of operations but in general it seems like a good use of the pattern. A quick search will turn up a lot of examples.

1

You need an Expression class, then a CompoundExpression and a TerminalExpression. What pattern does that sound like? Composite. Then you can parse using Visitor if you like.

When you provide a little language, whether it's arithmetic or some other interpreted set of commands, there are going to be compound commands, e.g. the expression 4 + (5 * 2) would be parsed into multiple commands and added to a CompoundExpression, which, when you called eval, it would iterate through its expression tree to compute the answer. (Design patterns are good for you, btw, learning them will make you a better coder.)

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.