Java:0 <= x <中的随机长数n 范围

人气:837 发布:2022-10-16 标签: java range random long-integer

问题描述

Random 类具有在给定范围内生成随机 int 的方法.例如:

Random class has a method to generate random int in a given range. For example:

Random r = new Random(); 
int x = r.nextInt(100);

这将生成一个大于或等于 0 且小于 100 的 int 数.我想对 long 数做同样的事情.

This would generate an int number more or equal to 0 and less than 100. I'd like to do exactly the same with long number.

long y = magicRandomLongGenerator(100);

Random 类只有 nextLong(),但它不允许设置范围.

Random class has only nextLong(), but it doesn't allow to set range.

推荐答案

从Java 7(或Android API Level 21 = 5.0+)开始你可以直接使用ThreadLocalRandom.current().nextLong(n)(对于 0 ≤ x

345