0

I'm making a quiz, but I'd like all the question's to be random, but never repeat each other. I have a question id and I need to generate a random integer after each question. I have 6 questions. Id's are from 1-7.

I have checked different topics, but they haven't solved my problem.

This is the code I have right now, but it repeats:

Random rnd = new Random();
    Integer n = rnd.nextInt(6) + 1;

    qid=n;

2 Answers2

3

Put your questions into an array and shuffle the array once. Pick the questions off the array in their shuffled order. That guarantees that there will be no repeats until all the questions are exhausted. Use Collections.shuffle(myArray); to do the shuffling.

rossum
  • 15,344
  • 1
  • 24
  • 38
  • I've tried this solution, but how can I pick numbers from a collection one by one? – Kaarel Reinvars Oct 24 '15 at 14:22
  • Pick the shuffled array elements in order: `myarray[1], myArray[2], ...` Keep track of where you are in the array with an index variable. – rossum Oct 24 '15 at 15:40
0

Try this method hope it may help you. this method is for 8 number

private void generateRandomNumber() {
    int rnd; Random rand=new Random();
    int[] randNo = new int[8];
    ArrayList numbers = new ArrayList();
    for (int k=0 ; k < 8; k++) {
        rnd = rand.nextInt(8) + 1;
        if(k==0) {
            randNo[0] = rnd;
            numbers.add(randNo[0]);
        } else { 
            while(numbers.contains(new Integer(rnd))) {
                rnd = rand.nextInt(8) + 1;
            }
            randNo[k] = rnd;
            numbers.add(randNo[k]);
        }
    }
}
Tunaki
  • 132,869
  • 46
  • 340
  • 423
Neeraj Sharma
  • 191
  • 18