2017-03-08 44 views
-6

我搜索了生成的,但它只有1个成员,如何做到这一点?!Java>生成很多int

Random rand = new Random();是可能的吗? 我要生成一个批号int 2之间,

但是,如果你想生成1 - 100号码使用:

for (int i = 1; i<=100; i++) 

例如:if 1-100产生:

1 
2 
3 
4 ... 
+2

使用for循环来确定您想要使用Random对象生成数字的次数。 –

+0

请查阅https://docs.oracle.com/javase/8/docs/api/java/util/Random.html#nextInt-int-。 – fvu

+1

对不起,现在看起来好像你可能要求循环像for(int i = 1; i <= 100; i ++){//用i}做某事。请使用[编辑]选项澄清你的问题。 – Pshemo

回答

2

在Java 8流,您可以使用两个数字之间生成一个整数流:

IntStream.range(lower, upper)... 

如果你希望他们被随机的,那么你可以使用:

Random random = new Random(); 
random.ints(count, lower, upper)... 

然后,您可以使用方法,如forEachreducecollect做的东西流。

因此,例如,random.ints(1000, 1, 100).forEach(i -> doSomething(i))将生成1到99之间的1000个随机数,并在它们中的每一个上调用doSomething

+0

当我使用system.out.println它不会返回良好的结果,但对于(int i = 1; i <= 100; i ++)没问题,谢谢 –

+0

值得一提的是'range'(lower,upper)'中的'upper'是唯一的。如果我们想要包含它,我们可以使用'rangeClosed'。 – Pshemo