Home >Java >javaTutorial >Generating random numbers in Java
There are two ways to generate random numbers in Java:
First, use the instance object of the Random class to generate:
Random r = new Random(); int i =r.nextInt(99)+1; //产生1-100之间的随机整数
Second, use the random number of the Math class () method generation:
int i= (int)(Math.random()*99+1); //产生的1-100之间的实数,强制类型取整
Let’s use specific code to demonstrate the specific usage
import java.util.Random;
public class RandomTest {
public static void main(String[] args) {
//利用Random类的实例
Random r = new Random();
int count=0;
System.out.println("Random类生成的数为:");
while(count<10){
int i =r.nextInt(99)+1;//产生1-100以内的随机数
count++;
System.out.println("第"+count+"个数为:"+i);
}
//利用Math类的random()方法
System.out.println("Math类生成的数为:");
int count1=0;
while(count1<10){
int i =(int)(Math.random()*99+1);//产生1-100以内的随机数
count1++;
System.out.println("第"+count1+"个数为:"+i);
}
}
}The above is the content of random number generation in Java, more For more related content, please pay attention to the PHP Chinese website (m.sbmmt.com)!