Reputation: 155
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
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
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
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