[英]Searching a class array with multiple values per record
我需要在对象数组中搜索名称,然后打印出与该名称相对应的所有信息。
我有
public class AccessFriendlyFile {
private Friendlies[] fr = new Friendlies[100];
private int size = 0;
public AccessFriendlyFile (){
try {
Scanner scFile = new Scanner(new File("Friends.txt"));
String line, name, surname, cell, mail, landline;
while (scFile.hasNext()){
line = scFile.nextLine();
Scanner sc = new Scanner(line).useDelimiter("#");
name = sc.next();
surname = sc.next();
cell = sc.next();
if (sc.hasNext()){
mail = sc.next();
landline= sc.next();
fr[size] = new ExtendFriendlies(name, surname, cell, mail, landline);
}
else {
fr[size]= new Friendlies(name, surname, cell);
}
size++;
sc.close();
}
}catch (FileNotFoundException ex){
System.out.println("File not found");
}
我该如何编码将在“ fr”中搜索名称并打印出所有相应信息的方法?
非常感谢杰西
编辑:这是我的搜索方法,当前不起作用。
public int Search(String name) {
int loop = 0;
int pos = -1;
boolean found = false;
while (found == false) {
if (fr[loop] == name) {
found = true;
pos = loop;
} else {
loop++;
}
}
return pos;
}
if语句上的类型比较错误。
在Friendlies
类中,有一个名为getName()
的方法,该方法将返回该Friendly的名称。 遍历fr
直到找到匹配的名称。 找到该名称后,请使用类似的get
方法为刚找到的匹配的Friendly
打印出所需的所有信息。
这应该工作:
public List<Friendlies> search(String name) {
List<Friendlies> list = new ArrayList<Friendlies>();
for(Friendlies friendlies : fr) {
if(friendlies.getName().equals(name)) {
list.add(friendlies);
}
}
return list;
}
然后,使用返回的列表,实现数据的漂亮显示:)
假设AccessFriendlyFile将数据加载到您的数组中,如果您要重新命名所有匹配的名称,可以对每个循环使用a:
List<Friendlies> getByName(String searched){
List<Friendlies> result = new Arraylist<Friendlies>();
for (Friendlies currentFriendly : fr){
if (searched.equalsIgnoreCase(currentFriendly.getName()){
result.add(currentFriendly);
}
}
return result;
}
仅针对第一个:
Friendlies getByName(String searched){
for (Friendlies currentFriendly : fr){
if (searched.equalsIgnoreCase(currentFriendly.getName()){
return currentFriendly;
}
}
return null;
}
您应该使用列表而不是固定数组。 如果文件包含100条以上的记录,则将出现indexoutofbounds异常。
我建议您在此处重命名变量。 我认为,Friendlies类存储一个联系人,一个Friend。 Friend对象的列表是一个数组,您可以将其命名为friendList甚至Friendlies。 我也鼓励您不要将size用作计数器变量。 大小是您有多少个朋友,您可以使用i或friendCounter遍历他们,也可以对每个循环使用a,如下文所示,
public Friendlies find(String name) {
for(Friendlies friend : fr) {
if(friend.getName().equalsIgnoreCase(name))
return fiend;
}
return null;
}
//now to print the info you can do this:
Friendlies findJoe = find("Joe");
if(findJoe==null)
System.out.println("You have no friends namd Joe.");
else
System.out.println(findJoe);
我的代码假定您在Friendlies中实现toString()。 如果使用netbeans,则可以自动生成此代码,然后对其进行调整以获取所需的格式。 (只需右键单击要在其中编写方法的位置,然后选择插入代码)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.