简体   繁体   中英

How to generate a random number in java with array bounds?

I want to ask how to generate a random number in java , i know it is done by random.nextint() but i want to check if the number is not what i wanted then it should be rejected and a new random number should be generated .

I want something like this :

Integer[] in = {1,2,3,4,5};    
int a = new Random().nextInt(10);
for(int i=0;i<in.length ;i++)
   if(a==in[i])
      //new random number

if the number is present in the above array (in) then new random number should be generated

Just put it in a do-while loop:

int a;
do {
    a = new Random().nextInt(10);
} while (Arrays.asList(in).contains(a));

I would avoid not generating a number you didn't want in the first place.

You can do either

int a = random.nextInt(5);
if (a > 0) a += 5;

or use a selection

int[] valid = { 0, 6, 7, 8, 9 }; // 0 to 9 but not 1,2,3,4,5
int a = valid[random.nextInt(valid.length)];

Simply call the method again. That is, if the number generated fits the if criteria then call a = new Random().nextInt(10);

Or, if your for loop ever regenerates a random number, you could just have the if statement do nothing ex: if(xyz){}; which of course would be pointless, and I think the original solution is probably what you seek.

To avoid any loops and retrying, try this:

    int [] in = {1,2,3,4,5};
    // generate integers from 0 up to the size of your array of allowed numbers:
    int index = new Random().nextInt(in.length); 
    int a = in[index]; // use the random integer as index for your array of allowed numbers

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM