繁体   English   中英

增加随机生成的数字

[英]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.

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