Home > Java > javaTutorial > Generating random numbers in Java

Generating random numbers in Java

黄舟
Release: 2017-01-18 15:36:35
Original
1399 people have browsed it

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之间的随机整数
Copy after login

Second, use the random number of the Math class () method generation:

int i= (int)(Math.random()*99+1); //产生的1-100之间的实数,强制类型取整
Copy after login

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);  
        }  
          
          
    }  
  
}
Copy after login

The above is the content of random number generation in Java, more For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template