相对较新的java虽然我已经编程了一段时间了.我想为我的女儿做一个有趣的数学项目,以帮助她学习数学将是一个简单的方法来测试java的能力.因此,为了尝试学习编程的有效方法,有没有办法将字符串或字符值从(/ , - ,+)转换为运算符/ - +?
例:
string/char textin = ""
text = JOptionPane "input box" ("*")
int results = 0
int num1 = 9
int num2 = 5
public static void calc(int num1,int num2, string/char textin)
{
results = num1 "some method"(textin) num2 // convert "*" to *
}
Run Code Online (Sandbox Code Playgroud)
这个问题的目的是减少所有四个运营商所需的计算量.使用一种通用方法来完成所有四个运算符.这可能吗?
不,那是不可能的.您最接近的是定义一个帮助器方法,该方法将字符串解释为运算符并应用它.
public static double operate(double x, double y, String operator) {
switch(operator) {
case "*":
return x*y;
case "/":
return x/y;
// etc.
default:
throw IllegalArgumentException("Unknown operator");
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
61 次 |
| 最近记录: |