[英]Increaing Randomly Generated Numbers
我想生成隨機整數,以便下一個生成的數字始終大於前一個數字。
假設我從3開始,我希望下一個始終大於3。並說我生成了5,我希望下一個大於5,依此類推。
這將為您提供一個始終大於先前值的數字。 范圍是您希望數字與上一個值之間的最大距離。
public getLargerRandom(int previousValue){
int range = 100; //set to whatever range you want numbers to have
return random.nextInt(range) + previousValue;
}
int rnd = 0;
while (true) {
rnd = ThreadLocalRandom.current().nextInt(rnd +1, Integer.MAX_INT);
System.out.println("Next random: "+rnd);
}
您可以將隨機生成的數字存儲為變量,然后將其用作下一代數字的最小值。
int x = 0;
x = new Random.nextInt(aNumber) + x;
下面的示例在起始值和最大值之間生成一組隨機數,而不會超過所需的最大數。
import java.util.Random;
public class RandomNumbers {
public static void main(String[] args) {
GetIncreasingInts(20, 3, 101);
}
public static void GetIncreasingInts(int numIntsToGet, int start, int max) {
if (numIntsToGet > 0 && start >= 0 && max > 0) {
Random random = new Random();
int nextStart = start;
int num = -1;
for (int index = 0; index < numIntsToGet; index++) {
if ((max - 1) <= nextStart)
break;
else {
num = nextStart + random.nextInt(max - nextStart);
nextStart = num;
System.out.println("Number: " + num);
}
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.