Android - 计算和存储算术表达式的答案

时间:2012-02-27 19:19:22

标签: java android math android-layout arithmetic-expressions

获得使用随机数和随机算子的问题的答案的最佳方法是什么。

  editTextEquation.setText(random1 +(String.valueOf(ops[i1]) + random2 +     (String.valueOf(ops[i2])+ random3 + (String.valueOf(ops[i3])+ random4))));

我正在显示此问题,然后将根据用户输入检查答案。我猜我需要先存储答案。任何帮助/建议将非常感谢。

以下是我如何生成表达式:

 int random1 = (int)(Math.random()*100);
 int random2 = (int)(Math.random()*100);
 int random3 = (int)(Math.random()*200);
 int random4 = (int)(Math.random()*20);

 int min = 0;
 int max = 3;
 Random r = new Random();
 int i1 = r.nextInt(max - min);
 int i2 = r.nextInt(max - min);
 int i3 = r.nextInt(max - min);

 char[] ops = { '+', '-', '/', '*' };

 int answer;

2 个答案:

答案 0 :(得分:1)

您需要多长时间才能坚持到底?

如果只是短时间,变量就足够了。

如果您需要很长时间,请考虑创建一个SQLite数据库来存储它。为表达式生成ID并将它们存储在数据库中。然后你可以在闲暇时间查看它们。

答案 1 :(得分:0)

如果您只有小问题,只有几个+-等,您可以尝试创建一个字符串来表示它,以及找到答案的基础操作,例如< / p>

public int calculate(int operation, int a, int b, int c) {
    if (operation ==1) {
        //must be all plus
        return a+b+c;
    }else if (operation ==2)
        //another case
        return a+b-c;
    }else if ( etc etc

}

public void displayQuestion(int operation, int a, int b, int c) {
   if(operation ==1) {
      System.out.println(a + " + " + b + " + " + c + " =");
   }else if( etc etc
}

然后,您可以显示每个问题,并根据具体情况请求答案。这是一种简单的方法,需要您指定每个案例。你可以很容易地让它变得更聪明,这是一种快速简单的方法,正确地完成它(将字符串解析为数学查询)有点困难,我需要回到我的实际工作中!