简体   繁体   中英

how to generate list of 5 random numbers between 20 and 100 in java

i want to generate list of 5 random numbers between 20 and 100.Here is my code

public class RandomNumbers {
    public static void main(String[] args){
        for(int i = 0; i < 5; i++){
            System.out.println((int)(Math.random() * 10));
        }
    }
}

Use this code (generates [from 0 to 80 ] + 20 => [from 20 to 100 ]):

public class RandomNumbers {
    public static void main(String[] args){
        for(int i = 0; i < 5; i++){
            System.out.println((int)((Math.random() * 81) + 20));
        }
    }
}

将计算设为Math.random() * 81 + 20

This will generate 5 random numbers between 20 and 100 inclusive.

 public class RandomNumbers {
        public static void main(String[] args){
            for(int i = 0; i < 5; i++){
                System.out.println(20 + (int)(Math.random() * ((100 - 20) + 1)));
            }
        }
    }

This used import java.util.concurrent.ThreadLocalRandom ;

for (int i = 0; i < 5; i++) {
    System.out.println(ThreadLocalRandom.current().nextInt(20, 100 + 1));
}

The nice thing is there is no number repetition and no need for prethought out math, which means changing values for max and min is incredibly efficient and less prone to error .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM