Search code examples
javaadditionscriptengine

Add numbers with the word "add"


I am writing to offer an application in Java right now and instead of using the operator "+", the user of the application can literally use the word "add" to add two numbers together.

I'm quite stuck on how to do this because I can't really use a method in order to complete the function considering I'd have to type "add()" rather than just "add". Unless there is a way to execute a method without the parentheses. Would I have to write a completely new class or is there an easier way to do this?


Solution

  • (An expansion on the idea presented by user710502)

    You can use reflection.

    double a = Double.parseDouble(some user input);
    double b = Double.parseDouble(some user input);
    String operation = some user input; // i.e. "add", "subtract"
    Method operator = Calculations.class.getMethod(operation, double.class, double.class);
    // NoSuchMethodException is thrown if method of operation name isn't found
    double result = (Double) operator.invoke(null, a, b);
    

    In some sort of calculations class:

    public static double add(double a, double b) {
        return a + b;
    }
    
    public static double subtract(double a, double b) {
        return a - b;
    }
    
    // and so forth