加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

将文件读入数组 – Java

发布时间:2020-12-15 04:27:27 所属栏目: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)
我正在练习 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++;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读