This question already has an answer here:
- Generating a random index for an array 3 answers
The problem I'm having is about efficiency. I want to return a random index of a string array. I only want the index to be between 0-2 but a random number between and equal to 0-2. The example code is below.
Random random= new Random();
int index= random.nextInt();
String animal;
String[] animalList= {"Dragon", "Goat", "Giant Goat"};
do {
if (index < 0)
index= index + 1;
else
index= index -1;
}while (index <0 || index >2);
System.out.println(animalList[index]);
Aucun commentaire:
Enregistrer un commentaire