Read file into array – Java
•
Java
I'm practicing Java and watching the exercise online:
But I'm in the situation I need
Read the file again,and initialise the elements of the array
task
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();
}
}
Content 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
Solution
It is basically the same as the calculation line:
int numOfLines = 0;
while(scan.hasNextLine()) {
scan.nextLine();
numOfLines++;
}
However, we now need to actually visit the next line Browse scanner docs quickly and tell me that nextline just returns what we want
int numOfLine = 0;
while(scan.hasNextLine()) {
String line = scan.nextLine();
members[numOfLine] = new MemberElement(line,numOfLine,/* birthDate */);
numOfLine++;
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
