[英]File Reader doesn't read all the data until the end
在person.txt中,我们存储了该人的详细信息。 好像是这样
John
Smith
aösldkjf
5
8645
asdfasf
0441234545
++++++
Adam
Gilchrist
ads
asf
asf
asfd
0441234546
++++++
然后,我们构建了FileManager类以从该文件中读取数据。 它标识有两个不同的条目。 但是它总是读取前8行,并且不会继续前进。 因此,第一个人(例如:-John Smith)被两次添加到名为“地址簿”的“ LinkedList”中。
//文件管理器类
public class FileManager {
public static void readFile() {
Scanner x;
LinkedList<String> tempList = new LinkedList<String>();
try {
x = new Scanner(new File("Person.txt"));
@SuppressWarnings("unused")
String temp = null;
while (x.hasNext()) {
tempList.add(x.next());
tempList.add(x.next());
tempList.add(x.next());
tempList.add(x.next());
tempList.add(x.next());
tempList.add(x.next());
tempList.add(x.next());
tempList.add(x.next());
Person person = new Person();
person.addFilePerson(tempList);
Main.addressBook.add(person);
}
} catch (Exception e) {
System.out.println("could't find the file");
}
}
}
// Person类中的addFilePerson方法
public void addFilePerson(LinkedList<String> list){
vorname = list.get(0);
nachname = list.get(1);
strasse = list.get(2);
hausnummer = list.get(3);
plz = list.get(4);
telefon = list.get(5);
wohnort = list.get(6);
}
您正在创建一个 LinkedList<String>
并将其重复添加。 移动这一行:
LinkedList<String> tempList = new LinkedList<String>();
进入while
循环。 或者-最好是IMO-对不同部分使用单独的属性:
// TODO: Consider what happens if the file runs out half way through a person...
while (x.hasNext()) {
Person person = new Person();
person.setFirstName(x.next());
person.setLastName(x.next());
person.setStreet(x.next());
person.setTown(x.next());
person.setTelephoneNumber(x.next());
person.setCity(x.next()); // Or whatever...
Main.addressBook.add(person);
}
为Person
创建一个“构建器”类型并使Person
本身不可变,还有其他选择,您可能要创建一个单独的Address
类型...
在从文件中读取人员之间,您应该清除(或重新创建)列表。 否则,您将继续在通讯录中添加同一个人(您阅读的第一个人)。 因此,或者按照Jon的建议每次在循环中重新创建临时列表,或者在每轮之后清除它:
while (x.hasNext()) {
tempList.add(x.next());
...
Main.addressBook.add(person);
tempList.clear();
}
它实际上继续前进。 这行:
person.addFilePerson(tempList);
您将tempList
作为参数发送,但是在addFilePerson
方法中,您始终会读取tempList
的前7个条目。 您应在循环的每次迭代中清除tempList
。
您应该使用nextLine()和hasNextLine()而不是next()和hasNext()。 扫描程序了解上下文,因此默认令牌读取行为可能不是基于行的。
你最好做
Person person = new Person();
Address address = new Address();
person.setAddress(address);
person.setFirstName(x.next());
person.setLastName(x.next());
address.setStreetName(x.next());
address.setHouseNumber(x.next());
address.setZipCode(x.next());
person.setPhoneNumber(x.next());
address.setCityName(x.next());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.