java - 数学运算符

标签 java android if-statement

我有这个方法会生成一个随机的数学表达式来解决它并将答案输出到一个变量:

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 语句会变得非常大。

有什么想法吗?

最佳答案

您可以使用内置的 Javascript 引擎。

import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;

public class Test 
{
  public static void main(String[] args) throws Exception
  {
       ScriptEngineManager mgr = new ScriptEngineManager();
        ScriptEngine engine = mgr.getEngineByName("JavaScript");
        String foo = "40+2";
        System.out.println(engine.eval(foo));
    } 
}

关于java - 数学运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9556682/

相关文章:

android - 无法从 apk/res-auto 命名空间访问项目资源

android - 如何在没有 Play 商店的情况下自动更新 Android 应用程序?喜欢 Facebook 应用或任何竞赛应用

javascript - 如何在 if 条件下检查变量是否相等?

java - 如果 Java 中的比较未命中

如果小于则 JavaScript 不工作

java - 我将如何在 Swing 中编写动态菜单栏?

java - 使用 fxml 在 JavaFX 中显示图像

java.sql.SQLException : ORA-12505, TNS:监听器当前不知道连接描述符中给出的 SID

java - 对 Swing 组件的反射(reflection)

android - 我可以使用 Eclipse 创建 Android 应用程序吗?