Is this for a school assignment or something? Why not just implement methods like add(int i), subtract(int i), etc. You'd need a single instance field -- value -- and you'd add to it or subtract from it in those methods. Much simpler. Something like:
And your test routine would be like:
Joined: Jan 15, 2007
But Max., I want be able to implement the calculator interface via this class, if I use your class is it possible.For ex:- 1 + 4 + 6 - 9=2, now in a calculator interface how can I invoke the add operation when + is pressed - operation when "- "is pressed using your class design?.
This is a exercise from the book Objects First With Java
Joined: Nov 06, 2000
Varuna: Oh, it's from a book. Since the person who made it up defined certain requirements, I'd have to see what he those are to comment on your implementation. Can you copy those here? Off hand, I'd avoid passing chars, such as + and -, to methods and have the code interpret them, since those are part of the user interface. In other words, you probably still need methods like add() and subtract(). If you wanted to get very OO, then you might code an Operator class, with subclasses like Add and Subtract. These could have a do(int operand1, int operand2), method that would do subtraction or addition or whatever. In this case, your calculator, or ALU class, would have an applyOperator(Operator o) method where'd you pass that in.
subject: For your advice on the Calulator so far developed