0
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);

    }
}

这段代码有问题吗??我无法搜索姓氏..请帮帮我

这是来自 Person 类

public String getLastName() { return lastName; }

4

1 回答 1

0

您的代码有什么问题,即使某些位置匹配,它也会为所有不匹配的位置打印出“找不到...”消息。也许这就是你想要的。但是,如果您想要一个lastName可以找到的位置,您可以执行以下操作:

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);
}

如果你想要找到它的所有位置,你可以这样做:

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());
}
于 2013-03-10T02:09:39.253 回答