Reputation: 5
I have an Integer array and I want to randomly take an element from those who are not null. I have tried this but after the else, I cannot use return because the method is int
. But I don't know what to write after else in order to return at the beginning and take a new random element.
public int getRandomPosition(){
Random x = new Random();
int b = x.nextInt(2*number0fCardPairs);
if (myArray[b] != null){
return b;
}
else{
return;
}
}
Upvotes: 0
Views: 94
Reputation: 83
You can achieve this by using a loop.
public int getRandomPosition(){
Random random = new Random();
int randomIdx = random.nextInt(array.length);
// while array at randomIdx is null, continue getting new randomIdx
while (array[randomIdx] == null) {
randomIdx = random.nextInt(array.length);
}
return randomIdx;
}
Note that if all the elements inside the array are null, it will be an infinite loop. Hope you find this helpful!
Upvotes: 1
Reputation: 1460
You could make your method recursive:
private Random x = new Random();
public int getRandomPosition(){
int b = x.nextInt(sizeOfArray);
if (myArray[b] != null){
return b;
}
// else {
return getRandomPosition();
}
or using a while-loop
private Random x = new Random();
public int getRandomPosition(){
Integer result = null;
do {
int index = x.nextInt(sizeOfArray);
result = myArray[index];
} while (result == null);
return result.intValue();
}
Theoretically, however, the method could run indefinitely if you're really unlucky. Therefore, it probably makes sense to include a counter, so for example only try max. 20 times, then return null
:
private Random x = new Random();
public int getRandomPosition(){
Integer result = null;
int tries = 0;
do {
int index = x.nextInt(sizeOfArray);
result = myArray[index];
} while (result == null && ++tries < 20);
return result.intValue();
}
Upvotes: 1
Reputation: 2776
You can do:
Integer[] myArray = {1,2,3,null,5};
List<Integer> nonNullIntegers = Arrays.stream(myArray)
.filter(Objects::nonNull)
.collect(Collectors.toList());
Random random = new Random();
Integer randomInteger = nonNullIntegers.get(random.nextInt(nonNullIntegers.size()));
Upvotes: 0