我正在练习java,并在网上查看练习:
然而,我陷入了我需要的地步
Read the file again, and initialise the elements of the array
Task
- 将表示成员列表的类 Members 编写为数组
- 构造函数应采用字符串参数(文件名)
- 使用扫描仪读取行并创建足够大的数组来容纳文件
- 再次读取文件并初始化数组元素
当前代码
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];
}
成员元素类:
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
它与计算行数基本相同:
int numOfLines = 0;
while(scan.hasNextLine()) {
scan.nextLine();
numOfLines++;
}
然而,我们现在需要实际access下一行。快速浏览一下扫描仪文档 http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html告诉我,那nextLine
返回的正是我们想要的。
int numOfLine = 0;
while(scan.hasNextLine()) {
String line = scan.nextLine();
members[numOfLine] = new MemberElement(line, numOfLine, /* birthDate */);
numOfLine++;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)