在arraylist中生成两次字符串元素

问题描述 投票:0回答:1

我遇到了问题。在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并添加多个方法中显示的元素但是再次崩溃。

java android arraylist random
1个回答
0
投票

这实际上取决于你的收藏generated如何实施。我会推荐HashSet<Integer>

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

© www.soinside.com 2019 - 2024. All rights reserved.