Java中的Random类

博客展示了Java中使用Random类生成随机数的实例。通过创建Random对象,调用其不同方法可生成任意大小的随机整数、布尔值、双精度浮点数、单精度浮点数、长整数等,还能生成指定范围的随机整数,每次运行结果随机。
Constructor Summary
Random()
          Creates a new random number generator.
Random(long seed)
          Creates a new random number generator using a single long seed:
 
Method Summary
protected  intnext(int bits)
          Generates the next pseudorandom number.
 booleannextBoolean()
          Returns the next pseudorandom, uniformly distributed boolean value from this random number generator's sequence.
 voidnextBytes(byte[] bytes)
          Generates random bytes and places them into a user-supplied byte array.
 doublenextDouble()
          Returns the next pseudorandom, uniformly distributed double value between 0.0 and 1.0 from this random number generator's sequence.
 floatnextFloat()
          Returns the next pseudorandom, uniformly distributed float value between 0.0 and 1.0 from this random number generator's sequence.
 doublenextGaussian()
          Returns the next pseudorandom, Gaussian ("normally") distributed double value with mean 0.0 and standard deviation 1.0 from this random number generator's sequence.
 intnextInt()
          Returns the next pseudorandom, uniformly distributed int value from this random number generator's sequence.
 intnextInt(int n)
          Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence.
 longnextLong()
          Returns the next pseudorandom, uniformly distributed long value from this random number generator's sequence.
 voidsetSeed(long seed)
          Sets the seed of this random number generator using a single long seed.

使用实例:
import java.util.Random;
public class RandomNum{
  public static void main(String[] args) {
      Random ran=new Random();
        System.out.println(ran.nextInt());//产生任意大小的随机整数
        System.out.println(ran.nextBoolean());//
        System.out.println(ran.nextDouble());//
        System.out.println(ran.nextFloat());//
        System.out.println(ran.nextLong());//
        System.out.println(ran.nextInt(100));//产生0至100的随机整数
  }
}

结果:
-1116918815
false
0.3570466757532643
0.69238234
7423008150361503085
88

由于结果是随记的每次运行的结果不同
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值