Probably a simple task for you guys, however I'm really struggling to make it work. I'm creating a method that can return random integers from 0-30. But I want to make sure, that the same numbers are not used twice. Therefore I created an array called UsedNumbersArray to keep track of everything.
My idea is that first it generates a random number, then it checks the array one by one using a for loop, to see if it's there. If that's the case, it must replace the value with zero, making sure that it won't be found again.
However what's weird is that it replaces a totally different number in the array than the one with our random number. Check out my code:
private static int checkIfNumberUsed(){
int questionNumber = randomNumberInRange(1,questionsWithAnswers[0].length); // create random number
boolean hasNotBeenUsed = false;
while (!hasNotBeenUsed){ // as long it HAS been used, it will continue to run the loop and create a random num till it gets what it wants
for (int i = 0; i < questionsWithAnswers[0].length ; i++) { // check if it has been used before
if (questionNumber==usedNumbersArray[i]){
usedNumbersArray[i]=0; // will replace the number with 0 so that it can't be found and used again
hasNotBeenUsed=true; // will exit the loop
}
}
questionNumber = randomNumberInRange(1,questionsWithAnswers[0].length); // if no matches are found it will generate a new random number
}
return questionNumber;
Here's the output:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30]
8 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 0, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30]
As you can see. The random number is 8, but it has replaced 18 with 0 instead of 8 as it was supposed to?
Hope you can figure this out. Thanks in advance