Discussions

General J2EE: Converting a String to Arithmetic operator

  1. Converting a String to Arithmetic operator (3 messages)

    Hi , I have a String from the database which will hold symbols + - etc. In the java code I should use this string as a operator to evaluate an expression like , say A + B = C where the plus sign is to be substituted by the String from DB..How do I accomplish this in Java...Any methods to parse Strings into arithmetic operators ?? Any help is highly appreciated. Thanks, Rajesh
  2. There are no such methods. There is no mechanism to convert a String to an operator. You will need to code if/switch blocks if (string.equals("+")) { do addtion etc
  3. There are no such methods. There is no mechanism to convert a String to an operator. You will need to code if/switch blocks

    if (string.equals("+")) {
    do addtion
    etc
    There are methods for this. Say, you have the String: String value = "A + B = C"; and you want to replace + sign with "plus" word for example. value.replaceAll("+", "plus"); this feature came with Java 1.4 Regards Onur.
  4. If you are able to use Java 5, you can try something like this... (It's far from a complete implementation, but it will point you in the right direction - feel free to give feedback/improve the code as you see fit) ------------------ import java.util.HashMap; import java.util.Map; public enum Operation{ PLUS("+"){ public double execute(double a, double b){ return a + b; } }, MINUS("-"){ public double execute(double a, double b){ return a - b; } }, TIMES("*"){ public double execute(double a, double b){ return a * b; } }, DIVIDE("/"){ public double execute(double a, double b){ return a / b; } }; private String symbol; private static final Map map = new HashMap(); static{ for (Operation operation : Operation.values()) { map.put(operation.getSymbol(), operation); } } private Operation(String symbol){ this.symbol = symbol; } public String getSymbol() { return symbol; } public abstract double execute(double a, double b); public static double apply(String symbol, double a, double b){ Operation operation = map.get(symbol); if(operation != null){ return operation.execute(a,b); } throw new UnsupportedOperationException("No operation support for symbol '" + symbol + "'"); } } ------------------------ And the test case for it ------------------------ import junit.framework.TestCase; public class TestOperation extends TestCase { public void testPlus(){ assertEquals(4.0, Operation.apply("+", 3, 1)); } public void testMinus(){ assertEquals(2.0, Operation.apply("-", 3, 1)); } public void testTimes(){ assertEquals(3.0, Operation.apply("*", 3, 1)); } public void testDivide(){ assertEquals(3.0, Operation.apply("/", 3, 1)); } public void testUnsupported(){ try{ Operation.apply("?", 3, 1); fail("This operation should throw an UnsupportedOperationException"); } catch(UnsupportedOperationException e){ //do nothing = we expect to get here } } }