在java中生成短随机数?

waq*_*qas 12 java random short

我想生成一个类型为short的随机数,就像有一个名为Random.nextInt(134116)的整数类型的函数一样.我怎样才能实现它?

luk*_*sen 22

没有Random.nextShort()方法,所以你可以使用

short s = (short) Random.nextInt(Short.MAX_VALUE + 1);
Run Code Online (Sandbox Code Playgroud)

+1是因为该方法返回的数字最多为指定的数字(不包括).看到这里

这将生成从0到Short.MAX_VALUE的数字(OP不要求负数)

  • @luketorjussen好的,我看看发生了什么.在约定之上是将.nextInteger(int top)作为.nextInteger()引用的方法.但是没有参数的Random.nextInteger()给出正数和负数,而Random.nextInteger(top)只给出正数.我认为将其明确地留给稍后阅读本文的其他人是有价值的. (2认同)

Ski*_*tol 11

Java短路包含在-32 768→+32 767间隔中.

你为什么不表演?

Random.nextInt(65536) - 32768
Run Code Online (Sandbox Code Playgroud)

并将结果转换为一个变量?

  • 我猜它并为你写了所以你会延长键盘的使用寿命. (4认同)

Pet*_*rey 9

能够产生所有可能的短值的最有效的解决方案是做任何一种.

short s = (short) random.nextInt(1 << 16); // any short
short s = (short) random.nextInt(1 << 15); // any non-negative short
Run Code Online (Sandbox Code Playgroud)

甚至更快

class MyRandom extends Random {
    public short nextShort() {
        return (short) next(16); // give me just 16 bits.
    }
    public short nextNonNegativeShort() {
        return (short) next(15); // give me just 15 bits.
    }
}

short s = myRandom.nextShort();
Run Code Online (Sandbox Code Playgroud)


ass*_*ias 6

怎么样short s = (short) Random.nextInt();?请注意,生成的分布可能存在偏差.Java语言规范保证这不会导致异常,int将被截断以适应简短.

编辑

实际上做了快速测试,结果分布似乎也是均匀分布的.