Jong Onin Jong Onin - 1 month ago 4
Java Question

JAVA: Searching for items in an arraylist only returns the first item

I have a Java program that ask for five string inputs from the user. My aim is to search for a particular element in the list containing 'a'. On running the code it can be seen that, it only returns the first occurrence of the element that has the element 'a'. list Eg: (aleah, alex, arthur, john, eerie).

Obtained Output:aleah.

Expected Output:It should have returned aleah, alex and arthur.

I have pasted my code below kindly have a look at it.

public ArrayList<String> searchName(String sn){
// String sn is the the search for character value (e.g 'a' or 'aa')
ArrayList<String> searches = new ArrayList<>();

for(String n : names){
// names list is declared in the other method and handles all the name values
// loop through the list. Am i using the right loop?
if(n.contains(sn)){
// if a specific index in the list contains the sn
searches.add(n);
// stored in in the new list searches
displaySearches(searches);
// called displaySearches and passed the arralist searches.
}

else
System.out.println("No results for " + sn);
break;
}


return searches;




}

public void displaySearches(ArrayList<String> searches){

for(String s: searches){
System.out.println(s);
// populates all the search results from the list.

}


}

rD. rD.
Answer

Your else statement is creating the problem here. Just remove it or place it outside the loop.

You can do something like this.

public ArrayList<String> searchName(String sn){ 

    ArrayList<String> searches = new ArrayList<>();

    //1. First add all the matches to the `searches` List.
    for(String n : names){ 
        if(n.contains(sn)){
            searches.add(n);
        }
    }

    //2. Now if the `searches` list is NOT empty, it means that 
    //   there were some matches, then display those matches
    if(!searches.isEmpty()) {
        displaySearches(searches);
    } else {
        //3. Otherwise print that there wasn't any match.
        System.out.println("No results for " + sn);
    }

    return searches;
}

public void displaySearches(ArrayList<String> searches){
    for(String s: searches){
        System.out.println(s);
    }
}