2017-03-08 43 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