Answer the question
In order to leave comments, you need to log in
Java. How to write random with an exception?
Tell me please. I need to assign a random array index to a variable, except for a specific one. How to implement it?
Answer the question
In order to leave comments, you need to log in
If I understand your problem correctly
int[] array = {1, 2, 3};
int badIndex = 1;
int variable;
int i;
Random random = new Random();
do {
i = random.nextInt(array.length);
}while (i == badIndex);
variable = i;
You create an array of valid indices, throw a random from 0 to the size of this array, take this random element of the array - it will be the index.
Pseudocode like this:
int[] validIndexes = {0,1,2,5,6,7,9,10};
int random = random.nextInt(validIndexes.length);
int validIndex = randomIndexes[random];
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question