Android - Generate non-repetitive random numbers [

2019-09-09 11:12发布

This question already has an answer here:

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条回答
淡お忘
2楼-- · 2019-09-09 11:27

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.

查看更多
Deceive 欺骗
3楼-- · 2019-09-09 11:42

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]);
        }
    }
}
查看更多
登录 后发表回答