【问题标题】:How to Loop over ten questions如何循环超过十个问题
【发布时间】:2012-03-03 11:45:47
【问题描述】:

我正在创建一个简单的数学游戏。我正在尝试创建一个循环,将十个问题,一次一个,显示到文本视图。用户将答案输入到编辑文本中,按下按钮,然后问题将被验证,并且十个系列中的下一个问题将出现在文本视图中。

我只是不太确定如何回答下一个问题。任何帮助将不胜感激。

这是我到目前为止所做的:

int x = 0;

while (x < 10) {
  if (i1 == 1) {
    answer = q1;
    editTextEquation.setText(random1 + "+" + random2);
    x++;
  }
  if (i1 == 2) {
    answer = q2;
    editTextEquation.setText(random1 + "-" + random2);
    x++;
  }
  if (i1 == 3) {
    answer = q3;
    editTextEquation.setText(random1 + "/" + random2);
    x++;
  }
  if (i1 == 4) {
    answer = q4;
    editTextEquation.setText(random1 + "*" + random2);
    x++;
  }
}

然后验证按钮调用这个方法

private void questions() {
  int score = 0;
  int i = Integer.parseInt(editText.getText().toString());
  if (i == answer) {
    editText.setText("Correct");
    score++;
  } else {
    editText.setText("Incorrect");
  }
}

【问题讨论】:

  • 无法帮助您回答,但测试同一变量的整个多个 if 是 switch 语句的完美案例

标签: java android


【解决方案1】:

我建议如下(假设您想随机生成每个问题):

  • 定义一个String getQuestion() 方法,它将随机返回您的 生成的问题(两个随机数和一个随机操作数) 字符串
  • 定义boolean checkAnswer(String question, String answer)
    这将检查提供的答案是否适合提供的
    问题。

然后,当您点击“验证”按钮时,您

  • 打电话

    checkAnswer(yourQuestionsTextView.getText().toString(), yourAnswerField.getText().toString())

    并显示“正确”或 “假”使用Toast 取决于结果

  • 致电yourQuestionsTextView.setText(getQuestion())

【讨论】:

【解决方案2】:

你可以使用Creator的方式或者通过点击事件改变布局。每个布局都有自己的文本视图和按钮。您将只有一个 xml 和 viewflipper。在该布局中放置与您的问题、文本视图和按钮一样多的线性或相对布局。在java文件中,放

ViewFlipper vf = (ViewFlipper) findViewById(R.id.ID_OF_VIEWFLIPPER);

vf.showNext();

进入按钮的点击事件。然后它会改变布局并显示下一个问题。

【讨论】:

  • 如何让下一个 textview 和 edittext 覆盖旧的?
  • 本站有类似作品。 link &lt;TextView android:id="@+id/q1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:textColor="#000000" android:text="Hello" &gt; &lt;/TextView&gt; 比如上面的文本视图的文本是Hello。您将在那里写下问题。其实还有更好的办法。您应该在 string.xml 中创建您的问题并在 textview 中引用它,例如 android:text="@string/question1"
  • 不要忘记他们通过触摸来改变屏幕。你不会使用那种方式。您将为您拥有的每个按钮添加点击事件,并将我在第一个答案中编写的代码放入具有相应 textview id 的点击事件中。
【解决方案3】:

有一个方法getNextQuestion() 并在按钮单击Listener 中调用它。只需通过调用更改 TextView 中的文本

TextView.setText(Question)

有一个问题的 ArrayList 并在 getNextQuestion() 方法中传递索引或计数以显示下一个问题并在此之后增加索引/计数。

编辑: 将您的 Activity 中的字段设置为

int index=0;

并在你的方法中传递这个索引,这会改变文本。

 getNextQuestion(index);

【讨论】:

  • 谢谢您的回复。如何在 getNextQuestion() 方法中传递索引并增加索引?
猜你喜欢
  • 2021-05-10
  • 2018-08-11
  • 1970-01-01
  • 1970-01-01
  • 2015-03-03
  • 1970-01-01
  • 2019-04-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多