我有一个 while 语句,它生成 15 到 32、212 到 229 之间的数字。
import java.util.Scanner;
import java.util.Random;
public class Test
{
public static void main(String[] args)
{
int randNum = 0;
Random randNumList = new Random();
while( !(randNum>=15 && randNum<=32)&& !(randNum>=212 && randNum<=229))
{
randNum = randNumList.nextInt(251);
}
System.out.println(randNum);
我可以使用什么类型的循环来生成给定数量(例如 10)的这些“randNum”?例如,如果 while 语句生成数字 24,我如何从该 while 语句中生成 15/32 到 212/229 之间的另外 10 个数字?
最佳答案
虽然您创建随机数的方式可能不是最有效的 - 对代码的侵入性最小的更改是将您的 while 简单地包装在 for 循环中...您可以将结果添加到数组或列出以便稍后访问它们。
Random randNumList = new Random(); //do this only once - no need to re-create it you can re-use it
for(int i=0; i<asManyAsYouWantPlusOne; i++){
randNum = 0; //important! reset here or you will end up with all the same random numbers ...
while( !(randNum>=15 && randNum<=32)&& !(randNum>=212 && randNum<=229))
{
randNum = randNumList.nextInt(251);
}
//add to list, or array here ...
System.out.println(randNum);
}
关于java - While 语句的循环解决方案?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26267598/