greeninho

02-26-2012, 07:36 AM

Happy sunday to all. I have been to write programs on simple arithmetic operations but i encountered a problem trying to put the whole individual operation as one program. What i mean is that want a situation where if (an assumption) both an additional and a subtraction program are written as one program, whereby one is given an option of like 'click here to add or subtract' something of that kind. I need help on how to go about it, hope my thread is clear and understandable?

Fou-Lu

02-26-2012, 07:08 PM

Since we have no idea what you have done, I can only suggest routes in which you can decouple the arithmetic control from the calculator itself. For that, a simple interface, a calculator, and each class written individual would work fine. This one I wrote a calculator with a hashtable to register ops to the calculator. Wrote a simple main test without any error checking in it, and it works fine:

package calc;

public interface IOperation

{

public void registerOperation(Calculator calc);

public double calculate(double lhs, double rhs);

}

// Add

package calc;

public class Add implements IOperation

{

public Add(Calculator calc)

{

this.registerOperation(calc);

}

@Override

public void registerOperation(Calculator calc)

{

calc.registerOperation("+", this);

}

@Override

public double calculate(double lhs, double rhs)

{

return lhs + rhs;

}

}

// Calculator

package calc;

import java.util.Enumeration;

import java.util.Hashtable;

import java.util.Scanner;

public class Calculator

{

private Hashtable<String, IOperation> htOps = new Hashtable<String, IOperation>();

public void registerOperation(String sOp, IOperation iOp)

{

this.htOps.put(sOp, iOp);

}

public IOperation getOperation(String sOp)

{

return this.htOps.get(sOp);

}

public double calculate(IOperation op, double lhs, double rhs)

{

return op.calculate(lhs, rhs);

}

public static void main(String... argv)

{

Scanner s = new Scanner(System.in);

double lhs, rhs;

String sOp;

StringBuffer opList = new StringBuffer();

int i = 0;

Calculator c = new Calculator();

new Add(c);

Enumeration<String> e = c.htOps.keys();

while (e.hasMoreElements())

{

if (i++ > 0)

{

opList.append(", ");

}

opList.append(e.nextElement());

}

System.out.print("Enter lhs: ");

lhs = s.nextDouble();

s.nextLine();

System.out.print("Enter ops (from list: " + opList + "):");

sOp = s.nextLine();

System.out.print("Enter rhs: ");

rhs = s.nextDouble();

s.nextLine();

System.out.println(c.calculate(c.getOperation(sOp), lhs, rhs));

}

}

I used the console, but a gui would work fine as well.

Registering on the calculator is optional. The classes are easier written without the registration at all, but I liked the idea of giving a list of what the calculator could do.

Powered by vBulletin® Version 4.2.2 Copyright © 2016 vBulletin Solutions, Inc. All rights reserved.