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

How to use random class to generate random numbers in java

王林
王林 Original
2020-10-22 10:33:17 12917browse

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;

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; } }

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!

Statement:
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