用单词“ add”添加数字。 [英] Add numbers with the word "add"
问题描述
我正在写现在要用Java提供一个应用程序,而不是使用运算符 +,该应用程序的用户实际上可以使用单词 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.
我对如何执行此操作非常执着,因为考虑到必须键入 add( ),而不仅仅是添加。除非有一种方法可以执行不带括号的方法。我是否需要编写一个全新的类,或者有一种更简单的方法来做到这一点?
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?
推荐答案
(该想法的扩展由user710502呈现)
(An expansion on the idea presented by user710502)
您可以使用反射。
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);
在某些计算类别中:
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
这篇关于用单词“ add”添加数字。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!