Reputation: 3
I need to generate 100 random 3 digit numbers. I have figured out how to generate 1 3 digit number. How do I generate 100? Here's what I have so far...
import java.util.Random;
public class TheNumbers {
public static void main(String[] args) {
System.out.println("The following is a list of 100 random" +
" 3 digit numbers.");
Random rand= new Random();
int pick = rand.nextInt(900) + 100;
System.out.println(pick);
}
}
Upvotes: 0
Views: 19106
Reputation: 22128
This solution is an alternative if the 3-digit numbers include numbers that start with 0 (if for example you are generating PIN codes), such as 000, 011, 003 etc.
Set<String> codes = new HashSet<>(100);
Random rand = new Random();
while (codes.size() < 100)
{
StringBuilder code = new StringBuilder();
code.append(rand.nextInt(10));
code.append(rand.nextInt(10));
code.append(rand.nextInt(10));
codes.add(code.toString());
}
for (String code : codes)
{
System.out.println(code);
}
Upvotes: 0
Reputation: 8466
Try for loop
for(int i=0;i<100;i++)
{
int pick = rand.nextInt(900) + 100;
System.out.println(pick);
}
Upvotes: 2
Reputation: 7799
If you adapt the following piece of code to your problem
for(int i= 100 ; i < 1000 ; i++) {
System.out.println("This line is printed 900 times.");
}
, it will do what you want.
Upvotes: 2
Reputation: 347204
The basic concept is to use a for-next
loop, in which you can repeat your calculation the required number of times...
You should take a look at The for Statement for more details
Random rnd = new Random(System.currentTimeMillis());
for (int index = 0; index < 100; index++) {
System.out.println(rnd.nextInt(900) + 100);
}
Now, this won't preclude generating duplicates. You could use a Set
to ensure the uniqueness of the values...
Set<Integer> numbers = new HashSet<>(100);
while (numbers.size() < 100) {
numbers.add(rnd.nextInt(900) + 100);
}
for (Integer num : numbers) {
System.out.println(num);
}
Upvotes: 5
Reputation: 23289
Using the answer to the question Generating random numbers in a range with Java:
import java.util.Random;
public class TheNumbers {
public static void main(String[] args) {
System.out.println("The following is a list of 100 random 3 digit nums.");
Random rand = new Random();
for(int i = 1; i <= 100; i++) {
int randomNum = rand.nextInt((999 - 100) + 1) + 100;
System.out.println(randomNum);
}
}
Upvotes: 0