[英]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.