Android - Generate non-repetitive random numbers [

2019-09-09 11:14发布

问题:

This question already has an answer here:

  • Generating Unique Random Numbers in Java 17 answers

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;

回答1:

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.



回答2:

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