0

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));
        }
    }
}
Developer Limit
  • 155
  • 1
  • 3
  • 9
  • 3
    Possible duplicate of [How to generate random integers within a specific range in Java?](http://stackoverflow.com/questions/363681/how-to-generate-random-integers-within-a-specific-range-in-java) – Gooz Mar 11 '17 at 15:54

4 Answers4

2

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));
        }
    }
}
u32i64
  • 2,384
  • 3
  • 22
  • 36
1

Make the calculation be Math.random() * 81 + 20

Aaron Davis
  • 1,731
  • 10
  • 13
1

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)));
            }
        }
    }
Ali
  • 839
  • 11
  • 21
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.

Neil
  • 14,063
  • 3
  • 30
  • 51