public void searchLastName(String lastName)
{
int size = list.size();
for(int i = 0 ; i < size ; i++)
{
if(list.get(i).getLastName().equals(lastName))
System.out.print(lastName+ " is located at " +i);
else
System.out.println("Cant find at loc:" +i);
}
}
is there any problem with this code?? i cant search the lastName.. please help me guys
this is from class Person
public String getLastName() { return lastName; }
What's wrong with your code is that it will print out the "Can't find..." message for all locations that do not match, even if some locations do match. Perhaps that's what you want. However, if you want one location where lastName
is found, you can do something like this:
int found = -1;
for (int i = 0; i < size && found == -1; ++i) {
if (list.get(i).getLastName().equals(lastName)) {
found = i;
}
}
if (found >= 0) {
System.out.print(lastName+ " is located at " + found);
} else {
System.out.println("Cant find " + lastName);
}
If you want all locations where it is found, you can do this:
List<Integer> found = new ArrayList<Integer>();
for (int i = 0; i < size; ++i) {
if (list.get(i).getLastName().equals(lastName)) {
found.add(i);
}
}
if (found.isEmpty()) {
System.out.println("Cant find " + lastName);
} else {
System.out.print(lastName+ " is located at " + found.toString());
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.