How random numbers are generated in Java
1, System.currenttimemillis () method, the method returns the number of milliseconds from January 1, 1970 0:0 0 seconds to the current one, which can be used as a random number and can be modeled on certain numbers to limit the range of random numbers. This way, when multiple random numbers are generated at the same time in a loop, it is the same value and has some limitations!
Packagerandom number;/** * @authorYyx June 24, 2017*/ Public classCurrenttimemill { Public Static voidMain (string[] args) { for(inti=0;i<5;i++){ //gets the number of milliseconds from January 1, 1970 0:0 0 seconds to the current one long typeSystem.out.println (System.currenttimemillis () + ""); } }}
Operation Result:
1498288338862
1498288338862
1498288338862
1498288338862
1498288338862
2. Return a double value between [0,1] by Math.random ()
Packagerandom number;/** * @authorYyx June 24, 2017*/ Public classMathrandom { Public Static voidMain (string[] args) {//Loop produces 5 positive integers less than 100//Math.random () returns a double value between [0,1] for(inti = 0; I < 5; i++) { //Forced ConversionsSystem.out.println ((int) (Math.random () * 100) + "" +math.random ()); } }}
Operation Result:
82 0.7843678627543349
81 0.27864491675273717
5 0.4861832936232885
50 0.9897001939511756
85 0.299979261363151
3, through the random class to produce a random number, this is a professional random tool class, powerful
Packagerandom number;ImportJava.util.Random;/** * @authorYyx June 22, 2017*/ Public classRandomexample { Public Static voidMain (string[] args) {producerandom (); } /*** Randomly generates five integers less than 100*/ Public Static voidProducerandom () {Random R=NewRandom (); for(intj = 0; J < 5; J + +) {System.out.println (R.nextint (100)); } }}
Java get random number