-2

I tried looking at other similar topics about this issue, but none of them solved my issue. I have basically made an array, that consists of animal names, and I am trying to tell the computer to select a random animal name, but I don't know how to do that.

I've already tried to use math.random, but it always sends back a random index value which is just a number. I don't want it to send a random number, but a random string.

 String[] animalNames = {"Raven","Chameleon","Lion","Cheetah"};

So, I want to learn code that can allow the computer to randomely select an animal name. I expect it to input the animal name which is the element but not the index, which is just a number.

  • use the random index value as an index to access the array – Sharon Ben Asher Jun 23 '19 at 17:50
  • Get a [random integer](https://stackoverflow.com/questions/363681/how-do-i-generate-random-integers-within-a-specific-range-in-java) in the range zero to animalNames.length-1, then read the value of the array at that index. – ernest_k Jun 23 '19 at 17:51
  • I'm sorry, but I don't understand what you are trying to say, you see I just started doing a grade 11 computer science course as a grade 10, so I don't know much. – Anmol panchal Jun 23 '19 at 17:52
  • Hint: an array **maps** a number to a value. So, when you want to have a random value from an array, the only thing you need is a random number. A random **index**. Beyond that, there is also Collections.shuffle(). You can create a list of values, shuffle it, and simply return the first element. That works without the need to generate random numbers... – GhostCat Jun 23 '19 at 18:34

2 Answers2

0

You should generate a pseudo random int between 0 and array.length - 1 then return the value with that index n your array. You can use Random.nextInt() for that:

Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence.

Here is a full example:

String[] animalNames = {"Raven","Chameleon","Lion","Cheetah"};
Random random = new Random();
int randomIndex = random.nextInt(animalNames.length);
String randomAnimalName = animalNames[randomIndex];
System.out.println(randomAnimalName);
Samuel Philipp
  • 10,631
  • 12
  • 36
  • 56
0

My solution:

public String getRandomName (String [] animalNames){
Random rand = new Random(); 
int value = rand.nextInt(animalNames.length); // from 0 .. to animalNames.length - 1
return animalNames[value];
} 
sergkk
  • 118
  • 10