Analysis of Java random number and timer, analysis of java Random Number

Source: Internet
Author: User

Analysis of Java random number and timer, analysis of java Random Number

Generate a repeated random number of 90:

Public class RandomTest {public static void main (String [] args) {/** Math. the random () method defaults to the double type, so it must be forcibly converted to int */int x = (int) (Math. random () * (100-90 + 1) + 90); // (max-min + 1) + min = min-max System. out. println (x );}}

Generate a random number of 90-distinct values:

Import java. util. hashSet; import java. util. random; import java. util. set; public class RandomTest {public static void main (String args []) {int max = 100; // maximum int min = 90; // minimum int count = max-min; // number of Random numbers random Random = new Random (); Set <Integer> set = new HashSet <> (); // The hashset container can only store non-repeated objects while (set. size () <count) {// number of elements stored in hashset int x = random. nextInt (max-min + 1) + min; // generates a random number set. add (x); // add a random number to the hashset container} for (int I: set) {// foreach traverses the container element System. out. println (I );}}}

Each second generates a random number of 90-100 repetition:

Import java. util. random; import java. util. timer; import java. util. timerTask; public class RandomTest {void timer () {Timer timer = new Timer (); // create a timer object timer. schedule (new TimerTask () {public void run () {// run method of the Runnable interface of TimerTask = new Random (); int x = random. nextInt (100-90 + 1) + 90; // (max-min + 1) + min = min to max // int x = random. nextInt (100) % (100-90 + 1) + 90; // the same effect as System. out. println (x) ;}}, 1000); // 0 indicates no delay, ms = 1 s} public static void main (String [] args) {RandomTest ran = new RandomTest (); ran. timer (); // call a scheduled task }}

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.