In Java, there are two ways to get random numbers (generating a random number) is a familiar java.lang.Math.Random () static method, and the other is to create Java.util.Random objects. The following are the procedures used for two methods:
I. Java.lang.Math.random ()
When using this static method, we do not need to import any packages, because the java.lang.* package is loaded by default, and the following example uses the method:
public class RandomTest{
public static void main(String[] args){
int i=Math.random();//random()会自动产生一个0.0-1.0的双精度随机数
System.out.println(i);//输出
i=Math.random()*1000;//产生0-1000的双精度随机数
System.out.println(i);
int b=(int)(Math.random()*1000);//产生0-1000的整数随机数
System.out.println(b);
}
}
Two. Create a Java.util.Random object
import java.util.random
public class RandomTest{
public static void main(String[] args){
Random random=new Random();//创建random对象
int intNumber=random.nextInt();//获取一个整型数
float floatNumber=random.nextFloat();//获取一个浮点数(0-1)
double doubleNumber=random.nextDouble();//获取双精度数(0-1)
boolean booleanNumber=random.nextBoolean();//获取boolean数
System.out.println("intNumber:"+intNumber);
System.out.println("floatNumber:"+floatNumber);
System.out.println("doubleNumber:"+doubleNumber);
System.out.println("booleanNumber:"+booleanNumber);
}
}
Random use the current time as the cardinality when generating random numbers, we can system.currenttimemillis () to get the cardinality. Of course we can also specify the cardinality:
Random random=new Random (100);
The sequence of random numbers produced by the same cardinality is the same, which can be verified by the following procedure:
import java.util.random
public class RandomTest{
public static void main(String[] args){
Random random1=new Random(100);
Random random2=new Random(100);
for(int i=0;i<5;i++){
System.out.print(random1.nextInt()+"\t");
System.out.println(random2.nextInt()+"\t");
System.out.println("---------------------------------");
}
}
}
We can see that the random numbers produced by RANDOM1 and Random2 are the same.