问题
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