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
Try removing the static
keyword when you declare you variables in your hero class. So instead of
static String name;
...
static int flight;
do
String name;
...
int flight;
Making them static
makes it so the variable is not specific to a single instance of the class, but rather the class as a whole. Static variables can be called upon without instantiating an object of the class.
For example, with your current code
hero.flight
would also return 7. By removing the static
identifier you will be able to make each of the variables specific to each object in your array.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.