オブジェクトの配列 (名前と数値の配列) がありますが、新しいオブジェクトが配列に正しく格納されていません。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
そして、これは変更が発生したときの出力です (配列のインデックス、新しい名前、オブジェクトの 2 番目の部分の新しい番号、および配列の位置 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]
Name クラスは次のとおりです。
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...
}
事前に感謝します。このサイトは非常に便利で、最後の任務で今までここに投稿する必要はありませんでした。