【问题标题】:Generates twice a string element in arraylist在arraylist中生成两次字符串元素
【发布时间】:2019-02-18 04:03:00
【问题描述】:

我遇到了问题。在我在 android studio 中的测验应用程序中。 所以,当你开始测验时,它应该随机给出问题,但有时它会出现两次。

public void updateQuestion(){
    int numOfQuestion = 0;
    while(true){
        int nxt = rng.nextInt(qsts.size());
        if(numOfQuestion < 10){
            if(!generated.contains(nxt)){
                generated.add(nxt);
                nextQuestion = qsts.get(nxt);
                question_tv.setText(nextQuestion.questionText);
                allAnswers.add(nextQuestion.correctAnswerText);
                allAnswers.add(nextQuestion.wrongAnswer1);
                allAnswers.add(nextQuestion.wrongAnswer2);
                allAnswers.add(nextQuestion.wrongAnswer3);
                Collections.shuffle(allAnswers);
                button1.setText(allAnswers.get(0));
                button2.setText(allAnswers.get(1));
                button3.setText(allAnswers.get(2));
                button4.setText(allAnswers.get(3));
                numOfQuestion++;
            }
        }else{
            //GameOver();
        }
    }
}

所以我的班级是:

public class QA {
    String questionText;
    String correctAnswerText;
    String wrongAnswer1;
    String wrongAnswer2;
    String wrongAnswer3;
    QA(String qst, String cAns, String wAns1, String wAns2, String wAns3){
        questionText = qst;
        correctAnswerText = cAns;
        wrongAnswer1 = wAns1;
        wrongAnswer2 = wAns2;
        wrongAnswer3 = wAns3;
    }
}

以及对象的格式

QA q1 = new QA("Question", "CorrectAns", "WrongAns1", "WrongAns2", "WorngAns3");

我试图删除出现的元素,

qsts.remove(generated);

或;

qsts.remove(nxt);

但是应用崩溃了... 还尝试创建一个空的 ArrayList 并添加在多个方法中显示但再次崩溃的元素。

【问题讨论】:

  • 因为您只需要独特的问题,您可以使用Set
  • 你可以检查列表是否不包含问题然后添加它,否则什么都不做

标签: java android arraylist random


【解决方案1】:

这实际上取决于您的集合generated 是如何实现的。我会推荐HashSet&lt;Integer&gt;

为了代码效率,切换条件 - 首先检查重复项,然后检查问题数量。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-02-28
    • 1970-01-01
    • 1970-01-01
    • 2021-03-03
    • 2019-01-24
    • 1970-01-01
    • 2020-08-02
    相关资源
    最近更新 更多