Summary of random number generation methods in Java programming

This chapter first explains several ways of generating java random numbers, and then demonstrates them through examples. Broadly speaking, there are three ways to generate random numbers in Java: (01) Through system Currenttimemillis() to get a long number of milliseconds of the current time. (02). Via math Random () returns a double value between 0 and 1. (03). Generate a random number through the random class. This is a professional random tool class with powerful functions. The first uses system Currenttimemillis() gets the random number through system Currenttimemillis() to get the random number. In fact, it gets the current time in milliseconds, which is of type long. The method of use is as follows:

To get an integer of type int, just convert the above result to type int. For example, get the int integer between [0100]. The method is as follows:

The second uses math Random() gets the random number through math Random() to get a random number. In fact, it returns a double value between 0 (inclusive) and 1 (exclusive). The method of use is as follows:

To get an integer of type int, just convert the above result to type int. For example, get the int integer between [0100]. The method is as follows:

The third method uses the random class to obtain random numbers, and uses the random class to obtain random numbers. The usage method is as follows: (01) create a random object. There are two ways to create a random object, as follows:

(02) obtain the random number through the random object. Random supports the following random value types: Boolean, byte, int, long, float and double. For example, get the int integer between [0100]. The method is as follows:

Random function interface

Get random number example

EG1: the following is an example to demonstrate the above three methods of obtaining random numbers. The source code is as follows (randomtest. Java):

eg2:

Problem: generate a random number with two digits after the decimal point between (- 10,10). Solution: 1 Random number generation function in java random r = new random(); r.nextFloat();// Generate floating-point random numbers between (0,1). Multiply the above random number by 10 to obtain the random number between (0,10). 2. Generate a Boolean random number to control the positive and negative of the number: r.nextboolean(); 3. Method of keeping two decimal places: math floor(n*100+0.5)/100; The number obtained is double. The code is as follows:

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>