我制作了一个电话账单系统,它可以输入电话号码、通话日期和通话时长,并将其保存到文本文件中。但是我无法在文本文件中搜索电话号码。以下是我的代码: 点击此处。
只需执行线性搜索(遍历您的电话列表):
public static List<Phone> searchPhone(final String phoneNumber, final List<Phone> phoneList) {
List<Phone> matchedPhone = new ArrayList<Phone>();
for(Phone phone: phoneList) {
if ( phone.getphoneNumber().equals(phoneNumber) ) {
matchedPhone.add(phone);
}
}
return matchedPhone;
}
为了易读性,不要将方法参数作为输出。这不是一个好的做法,因此您应该将方法更改为:
static void readList(List<Phone> phoneListIn) {
}
to:
static List<Phone> readList(final String fileName) {
}
尽可能避免使用输出参数
这是我在谷歌上找到的一些代码链接。
http://www.dreamincode.net/forums/topic/48905-search-inside-a-text-file/
首先执行Collections.sort(List list);
然后执行Collections.binarySearch(List list, Object key);
这样可以高效地进行搜索。