0

我正在创建一个简单的问答游戏。在这个游戏中,问题和相应的答案将随机生成。我为问题创建了一个列表“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 个错误。

4

2 回答 2

1

几天前我做了一个类似的测验应用程序(数学之王) 。

  1. 计算正确答案
  2. 将正确答案添加到您的答案列表中
  3. 计算假答案,将它们添加到答案列表中
  4. 随机播放列表
  5. 得到id正确答案的。它在 [0, max_answers) 范围内

如果已选择答案,则检查所选 id (0, 1, 2, 3) 是否是正确答案之一。如果是,则用户选择了正确的,否则他没有。

PS:对不起,自我推销。

于 2013-03-04T15:37:01.277 回答
0

如果这段代码能够正确编译和/或运行,我会感到惊讶。您正在尝试使用 a 的内容String作为变量名,将该变量转换为 anArrayList<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));
于 2013-03-04T15:59:53.247 回答