I have a problem comparing the number in the list so that it does not repeat using Random. I wanted the numbers to be random, but only those that are not on the list can be added. it is my code.:
List<Integer> list = new ArrayList<>();
int maxPosition = 5;
private void addToListNumber() {
int randomPosition = new Random().nextInt(5);
if (list.size() < 1) {
list.add(1);
addToListNumber();
} else if (list.size() < maxPosition) {
list.add(randomPosition);
addToListNumber();
} else {
for (Integer integer : list) {
System.out.println(integer);
}
}
}
Nevertheless the numbers repeat .. Maybe somebody explain why... I spent four hours on it and I can't figure out why the IF loop is passing the same number.
I'm sorry that my English is not perfect.
Aucun commentaire:
Enregistrer un commentaire