android:如何在随机问答的测验游戏中获得正确的答案列表?

时间:2013-03-04 15:32:31

标签: android string arraylist multiple-choice

我正在创建一个简单的问答游戏。在该游戏中,将随机生成问题和相应的答案。我在问题中创建了一个列表“q”

对于答案,我创建了各种列表,每个列表包含4个字符串。例如,如果问题是q列表中的0,则此问题的答案将在列表“a0”中,对吧?但我有一些问题要在答案列表中找到字符串。我试过这个:

    while(true){

            Integer nxt = rng.nextInt(6);

            if (!generated.contains(nxt))
            {
                generated.add(nxt);

                textView1.setText(((ArrayList<String>) q).get(nxt));

                String x;
                x = ("a" +nxt); 

                Collections.shuffle((x));

                btn1.setText(((ArrayList<String>) x).get(0));
                btn2.setText(((ArrayList<String>) x).get(1));
                btn3.setText(((ArrayList<String>) x).get(2));
                btn4.setText(((ArrayList<String>) x).get(3));


                break;
            }
    }

我创建了一个字符串“x”来获取正确的列表。如果“nxt”为4,则按钮文本将获得列表a4中的字符串。

但在我的代码中,“Collections.shuffle”“setText”尝试查找列表“x”。它不会像我想象的那样。

我该如何解决?

*我的想法是检查点击按钮的字符串并与另一个正确答案列表进行比较。通过这种方式,我可以归咎于正确的答案而另外3个错误。

2 个答案:

答案 0 :(得分:1)

我几天前做了similar quiz app (King of Math)

  1. 计算正确答案
  2. 在答案列表中添加正确答案
  3. 计算假答案,将其添加到答案列表
  4. 随机播放列表
  5. 获取正确答案的id它在[0,max_answers]范围内
  6. 如果选择了答案,则检查所选的ID(0,1,2,3)是否是正确答案之一。如果是,用户选择了正确的,否则他没有。

    PS:对不起自我推销。

答案 1 :(得分:0)

如果这段代码能够正确编译和/或运行,我会感到惊讶。您正尝试使用String的内容作为变量名称,将该变量强制转换为ArrayList<String>,然后访问这些元素。这在很多层面上是错误的,你应该考虑再做一些Java教程。

如果您确实或仍然认为可以继续,请尝试以下方法:您不应将问题和答案存储在单独的列表中,而应将其存储在一个类中。

class Question
{
    //...
    // maybe id and other stuff belonging to a question
    //...

    String questionText;

    // separate because you need to tell the correct answer apart from the wrong ones later
    // you could also just always use the first one in a set of answers.
    String correctAnswerText; 
    ArrayList<String> wrongAnswerTexts;
 }

然后,您可以将问题存储在应用中的ArrayList<Question>中,并按如下方式设置答案:

//...
// set up ArrayList<Question> questions here
//...

int nxt = rng.nextInt(6);

//...    
// make sure your list is actually long enough for the generated index
//...

Question nextQuestion = questions.get(nxt);

//...    
// make sure the retrieved object is valid
//...    
// set the question text to nextQuestion.questionText;
//...

ArrayList<String> allAnswers = new ArrayList<String>();
allAnswers.add(nextQuestion.correctAnswerText);
allAnswers.addAll(nextQuestion.wrongAnswerTexts);

Collections.shuffle(allAnswers);

btn1.setText(allAnswers.get(0));
btn2.setText(allAnswers.get(1));
btn3.setText(allAnswers.get(2));
btn4.setText(allAnswers.get(3));
相关问题