简体   繁体   English

从随机生成的数字中提取特定数字

[英]extract specific numbers from randomly generated

New to Java. Java的新手。 Not complete beginner but almost. 不是完整的初学者,但是差不多。

I'd like to generate 9 numbers between 9 and 18 and extract #1 and #5. 我想在9和18之间生成9个数字,并提取#1和#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! 您可以将所有9个生成的数字保存在一个数组中,并从中获得第一个和第五个!

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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