mercredi 14 novembre 2018

How do I assign random values to objects?

I am creating a card game that requires the cards to have random attributes. So I created a card class:

public static class hero{
static String name;
static int strength;
static int intellect;
static int flight;
static int tech;
}

The user then enters the number of cards and an array of cards (objects) is created.

hero [] cards = new hero[cardNumber];
           for(int i=0;i<cardNumber;i++){ cards[i]=new hero();}

However, when I try to assign random values to the cards using a for loop every card's attribute end up having the same value, this is the code I used:

for(int i=0; i<cards.length; ++i)
           {
           cards[i].strength = rand.nextInt(25) + 1;
           cards[i].intellect = rand.nextInt(25) + 1;
           cards[i].flight = rand.nextInt(25) + 1;
           cards[i].tech = rand.nextInt(25) + 1;
           }

Eg.

cards[1].flight 

would return 7

cards[2].flight 

would return 7

I am pretty sure I am wrong and any help and guidance is highly appreciated




Aucun commentaire:

Enregistrer un commentaire