将文件读入数组-Java [英] Reading File into Array - Java

查看:319
本文介绍了将文件读入数组-Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在练习Java,并在网上看练习:

I am practicing java, and looking at exercises online:

但是,我被困在需要的地方

However, I am stuck at the point in which I need to

Read the file again, and initialise the elements of the array


的元素

任务



  • 编写类代表列表的成员数组形式的成员

  • 构造函数应采用String参数(文件名)

  • 使用扫描仪读取行并创建足够大的数组来容纳文件

  • 再次读取文件并初始化数组元素

  • 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

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++;
}

但是,我们现在实际上需要访问下一行。快速浏览扫描仪文档告诉我,则 nextLine 完全返回我们想要的内容。

However, we now need to actually access that next line. A quick look into the Scanner docs tells me, that nextLine returns exactly what we want.

int numOfLine = 0;
while(scan.hasNextLine()) {
    String line = scan.nextLine();
    members[numOfLine] = new MemberElement(line, numOfLine, /* birthDate */);
    numOfLine++;
}

这篇关于将文件读入数组-Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆