0
請原諒我,因爲我是新手。 我的代碼讀取數字和名稱的文本文件。每個名字後面有3組數字,每組3個放入一個數組中。當數組被髮送到循環中的另一個類時,數組的內容會被覆蓋,我假設它只是引用數組的地址,而不是實際值。陣列被覆蓋的內容
public void readMarksData(String fileName) throws FileNotFoundException
{
File dataFile = new File(fileName);
Scanner scanner = new Scanner(dataFile);
int[] marks = new int[3];
scanner.nextLine();
int i = 0;
while(scanner.hasNext())
{
String studentName = scanner.nextLine();
while(i < 3)
{
try
{
marks[i] = scanner.nextInt();
i++;
}
catch (InputMismatchException ex)
{
i=0;
}
}
scanner.nextLine();
storeStudentRecord(studentName, marks);
//scanner.nextLine();
i=0;
}
scanner.close();
}
代碼在其他類
private void storeStudentRecord(String name, int[] marks)
{
//int[] x = new int[3]
StudentRecord student = new StudentRecord(name, marks);
marksList.add(student);
}
構造方法在另一類存儲值
public StudentRecord(String nameInput, int[] marksInput)
{
// initialise instance variables
name = nameInput;
noOfMarks = 0;
marks = marksInput;
}
這已被我逼瘋了好幾個小時,因此任何幫助將不勝感激,謝謝。
你重複使用相同的陣列。別。 Java傳遞引用,所以你最終得到一個'ArrayList',其中每個元素指向同一個內存位置。 –
另外,考慮使用「對象」而不是數組。 –
嘗試移動行int [] marks = new int [3];'在外'while循環中 –