Java get random number

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.