Having some trouble with a program I'm trying to write to imitate the card game 'Top Trumps', more specifically adding the Attributes of each Card to the ArrayList held by my class Card.
for (int i=1; i<5;i++)
{
int tempVal = rn.nextInt(10);
Card.attrbts.add(new Attribute ("Attribute "+i, tempVal));
System.out.println("Name: "+Attribute.name + " Value: " + tempVal); //debug
}
The program is supposed to randomly generate the value of each attribute and for simplicity I am just naming the each Attribute 'Attribute + i'.
The loop executes as expected for the most part, the value and names are generated fine as I can see from the debug statement, however, while this loop is adding elements to the ArrayList in my Card class it's using the same name and value for each element in the list, specifically the final iteration of my for loop (e.g. Attribute 4 and 6).
I was wondering if one of you could help explain to me why this is happening and how I'd go about fixing it?
Cheers
EDIT:
public class Card {
static ArrayList<Attribute> attrbts = new ArrayList<Attribute>();
String name;
public Card(String n, ArrayList<Attribute>attr)
{
this.name = n;
this.attrbts = attr;
}
public class Attribute {
static String name;
static int val;
public Attribute(String n, int v){
this.name = n;
this.val = v;
}