mardi 4 juin 2019

I would like a better, more efficient way to get a random index and return it to the main function [duplicate]

This question already has an answer here:

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