1.使用Math.util.Random类
方法有:
+Random() 构造函数
+Random(seed: long) 以特定种子构造对象(相同种子会返回相同随机数)
+nextInt(): int 返回随机整数
+nextInt(n: int): int 返回一个0到n之间的整数(不包括0和n),想要0可以这样:ra.nextInt(n+1)-1,n也想要就+2
+nextLong(): long 随机long整数
+nextDouble(): double 随机0.0到1.0之间(两边开区间)
+nextFloat(): float 同上,类型不同
+nextBoolean(): boolean 随机布尔值
像这样:
Random ra = new random(); int RandomInt = ra.nextInt();
2.使用Math.Random()
它返回的是[0, 1)的随机数。可以用:
(数据类型)(最小值+Math.random()*(最大值-最小值+1))
来返回闭区间的范围内随机数。(比nextInt慢一些,不是大量用没什么问题)
例如:
(int)(1+Math.random()*(10-1+1));
3.使用System.currentTimeMillis()
int number1 = (int)(System.currentTimeMillis() % 10);
int number2 = (int)(System.currentTimeMillis() * 7 % 10);
int number3 = (int)(System.currentTimeMillis() * 13 % 10);
这个方法是从UNIX时间戳以来到现在过去的毫秒数。
随便搞一个计算方法,让它看起来没什么规律就是了。当然个人感觉不算是很随机的随机数,毕竟是依靠时间的,不过既然运行时间不一定,那也够随机了