我正在练习
java,并在线观看练习:
但是,我陷入了我需要的地步
Read the file again,and initialise the elements of the array
任务
- Write class Members representing a list of members as an array
- Constructor should take String argument (file name)
- Use scanner to read lines and create array big enough to hold the file
- Read the file again and initialise 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
解决方法
它与计算线基本相同:
int numOfLines = 0; while(scan.hasNextLine()) { scan.nextLine(); numOfLines++; }
但是,我们现在需要实际访问下一行.快速浏览Scanner docs告诉我,nextLine正好返回我们想要的东西.
int numOfLine = 0; while(scan.hasNextLine()) { String line = scan.nextLine(); members[numOfLine] = new MemberElement(line,numOfLine,/* birthDate */); numOfLine++; }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。