Add numbers with the word “add”

时光毁灭记忆、已成空白 提交于 2019-12-12 00:31:44

问题


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?


回答1:


(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



回答2:


Just a little explanation on what you could do based on what the user enters:

int x = get it from the user;
int y = get it from the user;
string operation = get it from the user;
  • Create separate methods for the operations (i.e add(int x, int y), multiply(int x, int y), etc..)

Then create a method thag gets the values (x, y, string) say.. you can call it calculate(int x, int y, string operation)

Then in the calculuate method have a switch statement:

switch(operation)
{
case "add":
      add(x,y);
      break;
case "multiply":
      multiply(x,y);
      break;
etc...
}

Well, got you something to think about :).




回答3:


There's no way to do this in Java. You have two options:

1)Use a preprocessor. 2)Write it in a different language. You can write things in other languages and still have it compatible with Java classes and libraries.




回答4:


The consensus in comments seems to be 'Why would you want to do this? It is slow and cumbersome'. While the latter part is true, it is commonly done. See ScriptEngine as an example. Here is a demo of the JavaScript ScriptEngine in an applet.

The reader might note that ScriptEngine is an interface, suggesting an answer of 'implement your own script engine, based on the rules required'. Whether or not it is a good idea to create another scripting language, is left as an exercise for the reader.



来源:https://stackoverflow.com/questions/12023362/add-numbers-with-the-word-add

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!