How to have unique random number?

后端 未结 7 810
情深已故
情深已故 2020-12-16 08:38

This is how i am generating a unique no in between 1 to 6 and getting appropriate images from the drawable folder.

Random rand = new Random();
// n = the n         


        
7条回答
  •  死守一世寂寞
    2020-12-16 09:31

    Here's the easiest code to do it and store into an array without any repetition:

    Random rand = new Random();
    int[] ar;
    ar = new int[5];
    
    int random = 0;
    int [] result_arr=new int[5];
    boolean flag=false;
    
    for(int i=0;i<5;i++)
    {  
        ar[i]=0;
    
        do{
            random =rand.nextInt(10);
            flag=false;
            for(int j=0;j

    this will create unique numbers in the array

提交回复
热议问题