简体   繁体   中英

extract specific numbers from randomly generated

New to Java. Not complete beginner but almost.

I'd like to generate 9 numbers between 9 and 18 and extract #1 and #5. I have something for the generation but I have no idea how to extract a specific number from that.

I've got this for the generation :

Random rn = new Random();
int range = max - min + 1;
int randomNum =  rn.nextInt(range) + min;
            System.out.print(randomNum + " ");

Thanks very much for your help!!!

you could save all 9 generated numbers in an array and get the first and the 5th out of it!

Random rn = new Random();
int range = max - min + 1;
int[] rndNumbers = new int[9];

for (int i = 0; i < 9; i++) {
    rndNumbers[i] = rn.nextInt(range) + min;
}

rndNumbers[0]... //Do something with #1
rndNumbers[4]... //Do something with #5

Another possibility is to just save the first and fifth value:

Random rn = new Random();
int range = max - min + 1;
int first = 0, fifth = 0;

for (int i = 0; i < 9; i++) {
    int randomNumber = rn.nextInt(range) + min;
    if (i == 0)                                     // first element
        first = randomNumber;
    else if (i == 4)                                // fifth element
        fifth = randomNumber;
}

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