簡體   English   中英

如何在Java中搜索保存在我的arraylist中的lastName?

[英]how do i search lastNames saved in my arraylist in java?

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

    }
}

這段代碼有什么問題嗎? 我無法搜索姓氏。.請幫助我

這是來自班級的人

public String getLastName() { return lastName; }

您的代碼的問題在於,即使某些位置匹配,它也會為所有不匹配的位置打印出“找不到...”消息。 也許這就是您想要的。 但是,如果您想找到一個找到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());
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM