Use the math class method math. Random (); Use the random class in the Java. util package. Of course, the latter
It looks more professional and has a wider applicability.
1. Math. Random ()
Public static double random () // generates a random number from 0.0 to 1.0.
If we want to generate a random number of integer types, it is also feasible to use forced type conversion.
The following is a demo that generates a random number between 1 and 10.
Package
Framework;
Import java. util .*;
Public class demo {
Public static
Void main (string [] ARGs ){
System. Out. println ("generate a random number from 0 to 10 :");
For
(INT I = 0; I <10; I ++)
System. Out. Print (INT) (math. Random () * 10)
+ "");
// If You Want To generate a number between 0 and 100, it will be * 100, and so on.
}
}
2. Random class
In Java, you can use the java. util. Random class to generate a random generator. It has two constructor methods:
① Random () // use the current time, namely system. currenttimemills (), as the generator Seed
② Random (int
Seed) // use the specified seed as the generator Seed
After a random number generator is generated for a random object, different methods such as nextint (), nextlong (), and nextfloat () can be called to obtain different types of random numbers. Taking the int type as an example, there are two methods for overloading:
Int nextint ()
Int nextint (int n) // generates an integer random number from 0 to n
Example programs with the same functions as above:
Package framework;
Import java. util .*;
Public class demo {
Public static void main (string [] ARGs ){
System. Out. println ("generate a random number from 0 to 10 :");
Random random = new random ();
For (INT I = 0; I <10; I ++)
System. Out. Print (random. nextint (10) + ""); // to generate a random number in other ranges, you only need to change the N value.
}
}