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

Task

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

Current Code

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();

}

}

Contents Of Text File:

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

解决方案

It's basically the same like counting lines:

int numOfLines = 0;

while(scan.hasNextLine()) {

scan.nextLine();

numOfLines++;

}

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

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值