Home > Java > Javagetting Started > How to use random class to generate random numbers in java

How to use random class to generate random numbers in java

王林
Release: 2020-10-22 10:33:17
Original
13055 people have browsed it

Java uses the random class to generate random numbers: 1. Import the java.util.Random package; 2. Create a Random object; 3. Call the nextInt() function to generate random numbers.

How to use random class to generate random numbers in java

The java.util.Random class is used to generate random numbers. Need to import package:

(Recommended tutorial: java course)

import java.util.Random;
Copy after login

How to use random class to generate random numbers in java

Code implementation:

import java.util.Random;

public class RandomUtil {
    /**
     * nextInt(num) 产生[0 ~ (num-1)]的随机数, 闭区间
     * @param Min
     * @param Max
     * @return
     */
    public static int getRandomInt(int Min , int Max){
        Random rand = new Random();
        return rand.nextInt(Max - Min + 1) + Min;
    }
}
Copy after login

related Recommended: Getting Started with Java

The above is the detailed content of How to use random class to generate random numbers in java. For more information, please follow other related articles on the PHP Chinese website!

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