Random
Random:产生随机数的类
构造方法:
Random();
没有种子,使用的是默认种子。是当前时间的毫秒值。Random(long seed);
结出有效的种子,给定种子后,每次出现的随机数是相同的。
成员方法:
public int nextInt();
返回的是int范围内的随机数public int nextInt(int n);
返回的是(0.n)范围内的随机数,生成的是(0,n)的开区间的数。public double nextDouble();
返回下一个伪随机数,它是取自此随机数生成器序列的、在 0.0 和 1.0 之间均匀分布的 double 值
public class RandomTest {
public static void main(String[] args) {
//创建对象
// Random random = new Random();
Random random = new Random(1111);
for(int x= 0 ;x<10;x++) {
int num = random.nextInt(100)+1;
System.out.println(num);
}
}
}
结果:27 7 6 70 51 28 26 5 99 17
public class Demo02Random {
public static void main(String[] args) {
Random r = new Random();
for (int i = 0; i <5 ; i++) {
System.out.print(r.nextDouble()+" ");
}
}
}
结果:0.0011910175921947541 0.08550604700841791 0.4858359682484331 0.2766477348561561 0.8977107605644782
Math.random
public static double random();
返回带正号的double值,该值大于等于0.0且小于1.0,。返回值是一个伪随机选择的数,在该范围内(近似)均匀分布。
public class MathDemo {
public static void main(String[] args) {
System.out.println("random:"+Math.random());
System.out.println("random:"+((int) (Math.random()*100)+1));
}
}
random:0.3166464832091951
random:74
实例:获取start和end之间的随机数:
public static int getRandom(int start , int end) {
int number = (int)Math.random() * (end-start+1)+start;
return number;
}