【问题标题】:Android - calculating and storing the answer of an arithmetic expressionAndroid - 计算和存储算术表达式的答案
【发布时间】:2012-03-17 06:31:46
【问题描述】:

使用随机数和随机运算符来回答这个问题的最佳方法是什么。

  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;

【问题讨论】:

  • 看起来您将操作数存储为字符串,您是否考虑将它们存储为int/double,这应该会改变一些获取值的逻辑,并且意味着您每次都可以计算答案
  • 你能不能说的更准确一些,举个例子
  • @dann.dev,我该怎么做?只需将char更改为int?然后调整 setText 代码?
  • 对不起,问题看错了,看看我下面的答案,这是一种快速破解,但它会完成工作

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


【解决方案1】:

您需要坚持多久?

如果只是很短的时间,一个变量就足够了。

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

【讨论】:

  • 如何使用变量计算答案?
  • 创建一个 Expression 类来封装您的用户正在查看的表达式字符串,并给出一个 solution 成员。只要您还拥有Expression,您就会得到答案。至于计算答案,我想我假设你已经把那部分整理好了,因为你似乎对存储它更感兴趣。
【解决方案2】:

如果你只有小问题,那么只有+和-等几个,你可以尝试创建一个字符串来表示它,以及一个底层操作来找到答案,例如

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
}

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-04
    • 2020-04-16
    • 1970-01-01
    • 2011-01-25
    • 1970-01-01
    • 1970-01-01
    • 2014-03-10
    • 1970-01-01
    相关资源
    最近更新 更多