Developer Limit
Developer Limit

Reputation: 155

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

Upvotes: 0

Views: 9831

Answers (4)

Neil
Neil

Reputation: 14313

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.

Upvotes: 1

link
link

Reputation: 2419

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

Upvotes: 2

Ali
Ali

Reputation: 859

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

Upvotes: 1

Aaron Davis
Aaron Davis

Reputation: 1731

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

Upvotes: 1

Related Questions