arraylist仅将文件中的特定文本添加到数组列表,第2部分Java
我希望我能提出一些很好的建议来解决这个问题:
我有一个带有地名的文本文件——姓名详细信息表示此人去过的地方:
Place: New York
Place: London
Place: Paris
Place: Hongkong
1. Name: John
1. Name detail: London
1. Name detail: Paris
1. Name detail: Hongkong
2. Name: Sarah
2. Name detail: London
3. Name: David
3. Name detail: New York
3. Name detail: Paris
这是我代码的一部分
private ArrayList<Place> places = new ArrayList<>();
private ArrayList<Name> names = new ArrayList<>();
public void load(String fileName) throws FileNotFoundException {
ArrayList<Place> place = places;
BufferedReader br = new BufferedReader(new FileReader(fileName));
int nameCounter = 1;
int nameDetailCounter = 1;
String text;
try {
while ((text = br.readLine()) != null) {
if (text.contains("Place:")) {
text = text.replaceAll("Place:", "");
places.add(new Place(text));
} else if (text.contains(nameCounter + ". Name:")) {
text = text.replaceAll(nameCounter + ". Name:", "");
names.add(new Name(text, ""));
nameCounter ++;
}
//starting from here!
else if (text.contains(nameDetailCounter + ". Name detail:")) {
text = text.replaceAll(nameDetailCounter + ". Name detail:", "");
for (Name name : names) {
Name nameDetails = findName(name.getName());
Place placeDetails = findPlace(text);
nameDetails.addName(placeDetails);
}
nameDetailCounter ++;
}
}
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
}
我的想法是选择所有“1”首先从文本文件中,将其添加到数组中,然后继续执行所有“2”并将其添加到数组中,依此类推
我尝试了很多方法,但它没有在“1”开头添加所有名称细节在数组中。感谢您提出的任何新想法或建议,谢谢
# 1 楼答案
与其使用Name类,不如使用具有
String name
和List<Place> places
的Traveler类?然后就可以在Traveler类上有一个方法add(Place p)
# 2 楼答案
最好使用正则表达式来提取行中的数字,而不是试图跟踪/猜测它(见下文)
这是对代码的测试,因为您引用了一些未提供的类。。。但希望这能有所帮助: