java数学运算符
我有这样一种方法,它将生成一个随机数学表达式,求解它并输出变量的答案:
public int Nov2()
{
char[] ops = new char[] {'+', '-', '*', '/'};
int i = rand.nextInt(4-0) + 0;
char op1 = ops[i];
int novnum1 = rand.nextInt(101-1) + 1;
int novnum2 = rand.nextInt(101-1) + 1;
int nov2result = 0;
switch(op1) {
case '+': nov2result = novnum1 + novnum2; break;
case '-': nov2result = novnum1 - novnum2; break;
case '*': nov2result = novnum1 * novnum2; break;
case '/': nov2result = novnum1 / novnum2; break;
}
String nov2Exp = novnum1 + " " + op1 + " " + novnum2 + " = ";
Nov2resstor = nov2result;
setContentView(R.layout.gameview);
TextView display = (TextView) findViewById(R.id.exp);
display.setText(nov2Exp);
return nov2result;
}
在我的下一个方法中,我将如何对包含两个以上术语的表达式使用相同的方法,而不必编写非常复杂的if语句:
public int Eas3()
{
char[] ops = new char[] {'+', '-', '*', '/'};
int i = rand.nextInt(4-0) + 0;
char op1 = ops[i];
i = rand.nextInt(4-0) + 0;
char op2 = ops[i];
int easnum1 = rand.nextInt(101-1) + 1;
int easnum2 = rand.nextInt(101-1) + 1;
int easnum3 = rand.nextInt(101-1) + 1;
int eas3result = 0;
if (op1 == '+' && op2 == '+')
{
eas3result = ((easnum1 + easnum2) + easnum3);
}
else if (op1 == '+' && op2 == '-')
{
eas3result = ((easnum1 + easnum2) - easnum3);
}
else if (op1 == '+' && op2 == '*')
{
eas3result = ((easnum1 + easnum2) * easnum3);
}
else if (op1 == '+' && op2 == '-')
{
eas3result = ((easnum1 + easnum2) - easnum3);
}
.../
我有一些方法可以对2,3,4,5和6执行此操作,所以我的if语句将使用此方法变得非常大
有什么想法吗
# 1 楼答案
是的,另一种方法是编写命令对象:
您将编写一个实现此接口的对象:
现在,您可以使用运算符在地图中查找:
不需要开关
# 2 楼答案
你要找的是composite pattern。定义一个抽象的
Expression
基类并派生它这些类必须实现返回结果的
evaluate()
方法一个子类将是返回其值的常量,另一个子类将是一个二进制表达式,如加号、减号等。
evaluate()
方法将添加/减去/etc求值子表达式的结果然后,您可以从其他表达式中构建任意表达式,然后在不使用if条件的情况下对其求值
# 3 楼答案
Check out this MathEval class I found online它将为您计算表示方程式的字符串
# 4 楼答案
您可以使用内置的Javascript引擎
# 5 楼答案
使用递归如何:
当然,这会忽略操作的优先级
# 6 楼答案
您可以使用正在使用的变量创建一个字符串,如下所示:
之后,您可以使用ScriptEngineManager类将javascript用作引擎,以便使用eval方法
此方法执行计算并返回结果
希望这有帮助