生成不重复的随机数

生成不重复的随机数

本文介绍了Android - 生成不重复的随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一个测验,但我希望所有的问题都是随机的,但不要互相重复.我有一个问题 id,我需要在每个问题之后生成一个随机整数.我有6个问题.ID 为 1-7.

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;

推荐答案

将您的问题放入一个数组中,然后将数组打乱一次.按洗牌顺序从数组中挑选问题.这样可以保证在所有问题都用完之前不会重复.使用 Collections.shuffle(myArray); 进行改组.

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.

这篇关于Android - 生成不重复的随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 19:41