我有一个对象数组(一个名称和一个数字数组),它没有正确地将新对象存储在数组中。每次我尝试使用 for 循环添加一个新对象时,它都会覆盖以前的对象。请原谅我,因为我是新手,并且已经在这个问题上卡了几个小时。
/////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();
当我单步执行代码并在更改发生时打印出更改时,我看到位置 nameArray[0] 中的项目不断加载从文本文件中读取的最新数据集。以下是文本内容供参考。
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
这是更改发生时的打印输出(打印数组的索引、新名称、对象第二部分的新数字以及数组位置 0 中的数字)
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]
名称类如下:
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...
}
提前感谢,这个网站非常有用,直到现在,在我的最后一项任务中,我从来不需要在这里发帖。