我现在写信是为了提供一个 Java 应用程序,该应用程序的用户可以直接使用单词“add”将两个数字相加,而不是使用运算符“+”。
我对如何执行此操作非常困惑,因为考虑到我必须输入“add()”而不仅仅是“add”,所以我无法真正使用方法来完成该功能。除非有一种方法可以不使用括号来执行方法。我是否必须编写一个全新的类或者是否有更简单的方法来做到这一点?
最佳答案
根据用户输入的内容稍微解释一下您可以做什么:
int x = get it from the user;
int y = get it from the user;
string operation = get it from the user;
- 为操作
创建单独的方法(即 add(int x, int y)、multiply(int x, int y) 等)
然后创建一个方法 thag 获取值 (x, y, string) 说..你可以称之为 calculate(int x, int y, string opera)
然后在calculate方法中有一个switch语句:
switch(operation)
{
case "add":
add(x,y);
break;
case "multiply":
multiply(x,y);
break;
etc...
}
好吧,让你思考一下:)。
关于java - 添加带有单词 "add"的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12023362/