使用 apache-common lang3 生成隨機數
我們可以使用 org.apache.commons.lang3.RandomUtils
使用單行生成隨機數。
int x = RandomUtils.nextInt(1, 1000);
方法 nextInt(int startInclusive, int endExclusive)
佔用一個範圍。
除了 int 之外,我們可以使用這個類生成隨機 long
,double
,float
和 bytes
。
RandomUtils
類包含以下方法 -
static byte[] nextBytes(int count) //Creates an array of random bytes.
static double nextDouble() //Returns a random double within 0 - Double.MAX_VALUE
static double nextDouble(double startInclusive, double endInclusive) //Returns a random double within the specified range.
static float nextFloat() //Returns a random float within 0 - Float.MAX_VALUE
static float nextFloat(float startInclusive, float endInclusive) //Returns a random float within the specified range.
static int nextInt() //Returns a random int within 0 - Integer.MAX_VALUE
static int nextInt(int startInclusive, int endExclusive) //Returns a random integer within the specified range.
static long nextLong() //Returns a random long within 0 - Long.MAX_VALUE
static long nextLong(long startInclusive, long endExclusive) //Returns a random long within the specified range.