Home >Java >javaTutorial >How to use random in java

How to use random in java

下次还敢
下次还敢Original
2024-05-01 19:00:491114browse

The Random class in Java is used to generate pseudo-random numbers, including integers, real numbers and Boolean values. A random number generator can be generated using the current time or a specified seed. Commonly used methods include generating random integers (nextInt), random real numbers (nextDouble), random Boolean values ​​(nextBoolean) and random long integers (nextLong). Setting the seed ensures unpredictability when generating random numbers. The Random class is thread-safe.

How to use random in java

Usage of Random class in Java

The Random class in Java is used to generate Pseudo random numbers. It provides methods to generate random numbers of various types, including integers, real numbers, and Boolean values.

Constructor

Random The class has two constructors:

  • Random(): Use the current time as a seed to generate a random number generator.
  • Random(long seed): Generate a random number generator using the specified seed. The seed is a long integer used to initialize the sequence of random numbers.

Common methods

The following are the commonly used methods of the Random class:

  • int nextInt(): Generates a random integer in the range [Integer.MIN_VALUE, Integer.MAX_VALUE].
  • int nextInt(int bound): Generate a random integer within the range of [0, bound).
  • double nextDouble(): Generate a random real number in the range [0.0, 1.0).
  • boolean nextBoolean(): Generate a random Boolean value (true or false).
  • long nextLong(): Generate a random long integer.

Example

Here is an example of using the Random class to generate random integers:

<code class="java">import java.util.Random;

public class RandomExample {

    public static void main(String[] args) {
        // 创建一个随机数生成器
        Random random = new Random();

        // 生成一个随机整数
        int randomNumber = random.nextInt(100);

        // 打印随机整数
        System.out.println("随机整数:" + randomNumber);
    }
}</code>

Note

  • Random The random number sequences generated by the class are pseudo-random, that is, they are generated by a deterministic algorithm.
  • When using the Random class, setting the seed is important to ensure that unpredictable random numbers are generated.
  • Different seed values ​​will produce different random number sequences.
  • Random class is a thread-safe class.

The above is the detailed content of How to use random 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