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

How to use random class method in java

coldplay.xixi
Release: 2020-08-19 11:35:31
Original
5842 people have browsed it

Java uses random class methods: 1. Function [Random()] creates a new random number generator; 2. Function [Random(long seed)] uses a single long seed to create a new random number. Builder.

How to use random class method in java

Java uses the random class method:

Directly use the Math.random() method Method to generate random numbers.

//随机生成1~100之间的一个整数
        int randomNumber = (int)(Math.random() * 100) + 1;
        System.out.println(randomNumber);
Copy after login

There are also methods using the Random class.

  • Random(): Creates a new random number generator.

  • Random(long seed): Creates a new random number generator using a single long seed.

The first construction method is to use the default number of milliseconds of the current system time as the seed number: Random r1 = new Random();

Random random = new Random();
int randomNumber1= random.nextInt(100);
Copy after login

The second method is to use the seed number specified by yourself

Random random1 = new Random(100);
for(int i = 0; i < 10; i++){
System.out.print(random1.nextInt(10) + " ");
}
Copy after login

It is found that as long as the seed number is consistent with the parameters in nextInt(), the random number generated will be the same every time (so this is a pseudo-random number ).

System.out.println("\n使用同一种子生成的随机数如下:");
Random random2 = new Random(100);
for(int i = 0; i < 10; i++){
System.out.print(random2.nextInt(10) + " ");
}
Copy after login

The screenshots are as follows:

How to use random class method in java

Related learning recommendations: java basic tutorial

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