将文件读入数组 – Java

我正在练习 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++;
}

相关文章

Java中的String是不可变对象 在面向对象及函数编程语言中,不...
String, StringBuffer 和 StringBuilder 可变性 String不可变...
序列化:把对象转换为字节序列的过程称为对象的序列化. 反序...
先说结论,是对象!可以继续往下看 数组是不是对象 什么是对...
为什么浮点数 float 或 double 运算的时候会有精度丢失的风险...
面试题引入 这里引申出一个经典问题,看下面代码 Integer a ...