I have an Array of Objects (a name, and an array of numbers) that is not storing new Objects in the Array correctly. Each time I attempt to add a new object with a for loop it is overwriting the previous objects. Please forgive me as I am a novice, and have been stuck for hours on this problem.
/////INITIALIZE THE DATA/////////
// Read the Data and Return an Array of Objects from the text File
// Read in the info and calculate number of total lines.
Scanner scanFile1 = new Scanner(new FileReader("names2.txt"));
while (scanFile1.hasNextLine())
{
scanFile1.nextLine();
lines++;
}
scanFile1.close();
// Create array of objects
Scanner scanFile2 = new Scanner(new FileReader("names2.txt"));
nameArray = new Name[lines];
String tempName;
int[] tempArray = new int[DECADES];
for (int n = 0; n < lines; n++)
{
tempName = scanFile2.next();
for (int i = 0; i < DECADES; i++)
{
tempArray[i] = scanFile2.nextInt();
}
nameArray[n] = new Name(tempName, tempArray);
System.out.println(n);
System.out.println(tempName);
System.out.println(Arrays.toString(tempArray));
System.out.println(Arrays.toString(nameArray[0].popularityRanks));
scanFile2.nextLine();
}
scanFile2.close();
When I step through the code, printing out the changes as they happen I see that the items in location nameArray[0] keep getting loaded with the latest set of data being read from a text file. Here is the text contents for reference.
Bob 83 140 228 286 426 612 486 577 836 0 0
Sam 0 0 0 0 0 0 0 0 0 380 215
Jim 1000 999 888 777 666 555 444 333 222 111 100
And here is a printout of the changes as they happen (prints index of Array, new name, new numbers for second part of object, and numbers in location 0 of the Array)
0
Bob
[83, 140, 228, 286, 426, 612, 486, 577, 836, 0, 0]
[83, 140, 228, 286, 426, 612, 486, 577, 836, 0, 0]
1
Sam
[0, 0, 0, 0, 0, 0, 0, 0, 0, 380, 215]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 380, 215]
2
Jim
[1000, 999, 888, 777, 666, 555, 444, 333, 222, 111, 100]
[1000, 999, 888, 777, 666, 555, 444, 333, 222, 111, 100]
The Name class is as follows:
public class Name
{
public static final int DECADES = 11;
public static final int DECADE1900 = 0;
public static final int DECADE1910 = 1;
public static final int DECADE1920 = 2;
public static final int DECADE1930 = 3;
public static final int DECADE1940 = 4;
public static final int DECADE1950 = 5;
public static final int DECADE1960 = 6;
public static final int DECADE1970 = 7;
public static final int DECADE1980 = 8;
public static final int DECADE1990 = 9;
public static final int DECADE2000 = 10;
public String name = "err";
public int[] popularityRanks;
public Name (String name, int[] popularityRanks)
{
this.name = name;
this.popularityRanks = popularityRanks;
}
//...more methods to assess and work with the class...
}
Thanks ahead of time, this site has been so useful, I've never needed to post here until now, on my last assignment.