samedi 23 mai 2020

How can i pick Random Value from an Enum?

I want to learn how can i pick a string value from enum and run in for-each loop.

Let me write the Assignment here:

"Write a static method generateRandomZoo (n).

The method should have the parameter int n and the result should be an animal array of length n, the randomly chosen animal contains.

Proceed as follows:

  • First create one empty array of corresponding length.
  • Loop through the array.
  • Generate in a random value r for each run using the static method RandomTools.randomValue between 0 and Animal.values​​().length (exclusive).
  • Assign this to the current array position Enumeration element with the corresponding ordinal number for (Animal.values ​​() [r]). You can assume that n is positive."

What I've done is as follows:

First of all enum class looks like:

package main;

public enum Animal{

    ELEPHANT,LION, TIGER, WASP, SNAKE,MONKEY,  EMU;

}

and the main coding part is so:

public static void main(String[] args) {

    Animal[] zoo = generateRandomZoo(100);
}

private static Animal[] generateRandomZoo() {
    // TODO Auto-generated method stub

    Animal [] animals= new Animal [100];
    for(Animal a : Animal.values()){
        System.out.println("Random Animals"+ "-" + a + "-" +(a.ordinal()+1));

        for (int i = 0; i < 100; i++) {
            animal[i] = random animal
            System.out.println(i);
        }

        private static   RandomTools.randomValue();

    }

Could you please tell me where I am wrong and how to correct it ?

(By the way I am pretty beginner please describe in a way that i can understand:))




Aucun commentaire:

Enregistrer un commentaire