我在練Java和尋找練習在線:閱讀文件到數組 - Java的
不過,我停留在點上,我需要
Read the file again, and initialise the elements of the array
任務
- 寫作班成員列表成員列表
- 構造應採取字符串參數(文件名)
- 用掃描儀讀取線和創建數組大到足以容納的文件
- 再次讀取該文件,並初始化數組
當前的元素代碼
import java.io.*;
import java.util.*;
class Members {
MemberElement[] members;
public Members(String fileName) throws IOException {
File myFile = new File(fileName);
Scanner scan = new Scanner(myFile);
int numOfLines = 0;
while(scan.hasNextLine()) {
scan.nextLine();
numOfLines++;
}
scan.close();
scan = new Scanner(myFile);
members = new MemberElement[numOfLines];
}
MemberElement類:
class MemberElement {
private String name;
private int number;
private int birthDate;
public MemberElement(String name, int number, int birthDate) {
this.name = name;
this.number = number;
this.birthDate = birthDate;
}
public String getName() {
return this.name;
}
public int getNumber() {
return this.number;
}
public int getBirth() {
return this.birthDate;
}
public String toString() {
return getName() + " " + getNumber() + " " + getBirth();
}
}
內容的文本文件:
Wendy Miller 7654 17-2-1960
Dolly Sheep 4129 15-5-1954
Dolly Sheep 5132 21-12-1981
Irma Retired Programmer 345 15-11-1946
他們問你讀取文件兩次嗎?嗯 –
是的,首次讀取行數,然後關閉掃描儀。然後再次打開掃描儀以啓動陣列 – RandomMath
好的,您的具體問題在哪裏?第二次打開文件,還是讀取數組中的行? – fxnn