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 }}