I have looked at a lot of others,i still don't get how to input the non-repeat code into my code below.Newbie here,require someone to explain.
import java.util.Random;
class random{
public static void main(String[] args) {
Random dice = new Random();
int number;
for (int counter = 1; counter <= 20; counter++) {
number = 1 + dice.nextInt(100);
System.out.println(number + " ");
}
}
First add the random number to a set, this will stop duplicate entries. Then loop through and print out the set. There are a couple different ways you could do this but here is a way with the least amount of change to your code:
Set<Integer> numbers = new HashSet<Integer>();
Random dice = new Random();
int number;
for (int counter = 1; counter <= 20;) {
number = 1 + dice.nextInt(100);
if(numbers.add(number)) { //Only increment the counter if the number wasn't already in the set
counter++;
}
}
for(Integer num : numbers) {
System.out.println(num + " ");
}
A little bit simpler approach than suggested by MrMadsen is to control the set size:
Set<Integer> numbers = new LinkedHashSet<>();
Random dice = new Random();
while(numbers.size() < 20)
numbers.add(dice.nextInt(100)+1);
for(Integer num : numbers) {
System.out.println(num + " ");
}
Just for completeness here's Java-8 solution:
new Random().ints(1, 101).distinct().limit(20).forEach(System.out::println);
instead of just printing the random number have a set(which allows only unique elements) to capture the number and have a if condition to check the length of the set (set.size() == 20) come out of the loop until then you run the for loop to find the random numbers. I think this will solve your problem
Keep track of what is generated previously. Try this
public static void main(String...args) {
Random dice = new Random();
Set<Integer> previouslyGenerated = new HashSet<Integer>();
int number = 0,counter = 0;
while (counter <20){
number = 1+dice.nextInt(100);
if (!previouslyGenerated.contains(number)){
previouslyGenerated.add(number);
System.out.println(number + " ");
counter++;
}
}
}
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.