Home > OS >  How to generate random value from enum and put it in array?
How to generate random value from enum and put it in array?

Time:05-18

I got an enum which is filled with "items" and I want to generate one random item of the enum and put it into my inventory, which I made out of an array. The array only has room for 10 ints.

public class InventoryEnums {
    public static void main (String[] args){

    int[] inventar = new int[9] // int array mit 10 Plätzen

    enum items {
        KARTE, MONSTERBALL, MONSTERDEX, FAHRRAD, VM03, HYPERHEILER, AMRENABEERE, TOPGENESUNG, ANGEL, TOPSCHUTZ
    }

CodePudding user response:

You can get a random integer value that is in the range 0 to array.length as

int rand = new Random().nextInt(items.values().length);

Then you can get the enum for the random value generated using

items.values()[rand];

You then use this in a loop to fill the array.

CodePudding user response:

An enum should be named in the singular, and should start with an uppercase letter.

enum Item { KARTE, MONSTERBALL, MONSTERDEX, FAHRRAD, VM03, HYPERHEILER, AMRENABEERE, TOPGENESUNG, ANGEL, TOPSCHUTZ }

And I suggest you work at devising a more descriptive name than “Item”.

Get an array of all the enum objects by calling values.

Item[] allItems = Item.values() ;

Generate a random number. Use that number as the index into your array of all items.

int randomIndex = ThreadLocalRandom.current().nextInt( 0 , allItems.length ) ;  // ( inclusive , exclusive )
Item rando = allItems[ randomIndex ] ;

Or perhaps you meant to randomly sort (shuffle) all the elements of the enum.

Item[] allItems = Item.values() ;
List< Item > list = Arrays.asList( allItems );
Collections.shuffle( list );

More briefly:

Item[] allItems = Item.values() ;
Collections.shuffle( Arrays.asList( allItems ) );

The list is backed by the array. So changes made to the list also affect the array.

See this code run live at Ideone.com.

[MONSTERBALL, TOPSCHUTZ, KARTE, FAHRRAD, VM03, MONSTERDEX, ANGEL, AMRENABEERE, TOPGENESUNG, HYPERHEILER]

CodePudding user response:

Isn't this what you want?

public class App {
    public static void main(String[] args) {
        Random random = new Random();

        enum items {
            KARTE, MONSTERBALL, MONSTERDEX, FAHRRAD, VM03, HYPERHEILER, AMRENABEERE, TOPGENESUNG, ANGEL, TOPSCHUTZ
        }

        items[] inventar = items.values();

        int index = random.nextInt(inventar.length);

        System.out.println(inventar[index]);

    }
}

CodePudding user response:

There is another way:

  enum Item {
        KARTE, MONSTERBALL, MONSTERDEX, FAHRRAD, VM03, HYPERHEILER, AMRENABEERE, 
     TOPGENESUNG, ANGEL, TOPSCHUTZ
   }
   Item[] inventar = Item.values();
   Item singleItem = inventar[new Random().nextInt(inventar.length)];
  
  • Related