jeudi 13 septembre 2018

Generates twice a string element in arraylist

I got a problem. in my quiz application in android studio. So, when you start the quiz it should give questions randomly, but sometimes it appears 1 question twice.

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();
            }
        }
    }

so my Class is:

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;
    }
}

and the format of an object

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

I tried to remove the element which appears,

qsts.remove(generated);

or;

qsts.remove(nxt);

But the app crashed... Also tried to create an empty ArrayList and to add the elements which are shown in multiple methods but again crashed.




Aucun commentaire:

Enregistrer un commentaire