【问题标题】:Is there an Equivalent of .Net framework's Random.Next(Int32, Int32) in the Java API?Java API 中是否有 .Net 框架的 Random.Next(Int32, Int32) 等效项?
【发布时间】:2009-05-08 09:50:17
【问题描述】:

我正在将现有的 VB.Net 应用程序移植到 Java,但找不到与 Random.Next(Int32, Int32) 等效的应用程序。

我只能在 Java API 中找到 java.util.Random.next(int val)

Java API 中有 .Net 框架的 Random.Next(Int32, Int32) 的等价物吗?

【问题讨论】:

    标签: random java


    【解决方案1】:

    正如 Marc 所说,只需调整 Random.nextInt(int),并进行一些健全性检查:

    public static int nextInt(Random rng, int lower, int upper) {
        if (upper < lower) {
            throw new IllegalArgumentException();
        }
        if ((long) upper - lower > Integer.MAX_VALUE) {
            throw new IllegalArgumentException();
        }
        return rng.nextInt(upper-lower) + lower;
    }
    

    【讨论】:

    • 为什么这是必要的? if ((long) upper - lower > Integer.MAX_VALUE) { throw new IllegalArgumentException(); }
    • @MahdeTo:考虑 nextInt(rng, Integer.MIN_VALUE, Integer.MAX_VALUE)
    • (特别是想想在调用 rng.nextInt... 时会发生什么)
    【解决方案2】:

    不,但你可以这样:

    public static int randomInRange(int min, int max){
          return min+Random.next(max-min);
    }
    

    【讨论】:

      【解决方案3】:

      【讨论】:

        【解决方案4】:

        那么,您可以使用Random.nextInt(int) 指定范围,然后只添加最小值吗?即 rand.nextInt(12) + 5

        【讨论】:

        • rand.nextInt(max) + min 错误;这会返回大于 max 的整数吗?
        • 这就是为什么我使用了 range 这个词,而不是 max
        【解决方案5】:

        调用Random.Next(x, y) 可以翻译成类似Random.nextInt(y - x) + x;

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-05-30
          • 1970-01-01
          • 1970-01-01
          • 2019-04-28
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多