Java 如何从数组中随机生成数字,每个数字都是唯一的

Java 如何从数组中随机生成数字,每个数字都是唯一的,java,Java,我有一个数字数组,包含20个元素。我正在为黑莓应用程序随机显示数字,bt我想要数据生成的所有d数字都应该b唯一。它应该b随机生成,bt它有b唯一,直到数组中的所有元素都用尽。如果有人能帮我,我在这里给出代码,我将非常感激 static int quesNum[] = new int[20]; static int quesCount = -1; private static void initialize(){ Random rgen = new Random(); // Rand

我有一个数字数组,包含20个元素。我正在为黑莓应用程序随机显示数字,bt我想要数据生成的所有d数字都应该b唯一。它应该b随机生成,bt它有b唯一,直到数组中的所有元素都用尽。如果有人能帮我,我在这里给出代码,我将非常感激

static int quesNum[] = new int[20];
static int quesCount = -1;

private static void initialize(){

    Random rgen = new Random();  // Random number generator

    //--- Initialize the array 
    for (int i=0; i<quesNum.length; i++) {
        quesNum[i] = i;
    }

    //--- Shuffle by exchanging each element randomly
    for (int i=0; i< quesNum.length; i++) {
        int randomPosition = rgen.nextInt(quesNum.length);

        int temp = quesNum[i];

        quesNum[i] = quesNum[randomPosition];

        quesNum[randomPosition] = temp;

    }
}

/*Changed the code to get a unique random number

*/
public static int getQuestionNumber() {
    quesCount++;
    if(quesCount < quesNum.length){
        return quesNum[quesCount];
     }
    else{ 
       initialize();
       quesCount = -1;
       return getQuestionNumber();
    }
}
static int quesNum[]=new int[20];
静态int quescont=-1;
私有静态void initialize(){
Random rgen=new Random();//随机数生成器
//---初始化数组

对于(int i=0;i您所描述的是一个仅用于数组的完美应用程序。

您可以使用数组列表而不是数组,并删除每个生成的数字。

先洗牌,然后迭代:

Collections.shuffle(listOfValues);
for(Integer val : listOfValues) {
  // give it to user
}
更新

OP的一些措辞让我觉得Collections.shuffle()在Blackberry上不受支持。然后建议将Collections.shuffle(列表,随机)的代码复制到应用程序中。

int len=20;
int len = 20;
Integer[] arr = new Integer[len];
for(int i =0;i<len;i++){
    arr[i] = Integer.valueOf(i+1);
}
Collections.shuffle(Arrays.asList(arr));
整数[]arr=新整数[len];
对于(inti=0;如果您避免使用青少年缩写(例如“b”和“be”),我将非常感激。这会使阅读更困难。谢谢。