gloriousCatnip gloriousCatnip - 3 months ago 12
Java Question

New to Java, why doesn't this code work? i++ is 'dead code', and the function does not return a variable of desired type; even though it does

I am making a little program in Java that makes a program that acts like a "library", only with video games. In the program you shoud be able to add, delete and edit games; you shoud also be able to list off all the games in the "library".

To be able to delete and edit games, I have decided to implement a function that will return a list of all the elements in the list that matches the query String that I give it, and then the user will have to choose between a numbered list of all the returned results.

This is my code:

public static ArrayList<GameStorage> findElement(ArrayList<GameStorage> gameList, String query) {
ArrayList<GameStorage> temp = new ArrayList<GameStorage>();
for(int i = 0; i < gameList.size(); i++) {
if(gameList.get(i).getName().contains(query)) {
temp.add(gameList.get(i));
}
return temp;
}
}


I initialize an empty GameStorage ArrayList, and use this to store all the desired elements and then return it. However, this does not work at all and Eclipse says that the
i++
part is supposedly 'dead code' (and this supposedly means that the code never is reached), the function also says that I do not return a result of the desired type
ArrayList<GameStorage>
, even though I do. I don't know what I've done wrong.

Could someone perhaps enlighten me?

Answer

return should be after your loop body, not the last statement. Because it is the last statement i++ is never reached. Change it like

for(int i = 0; i < gameList.size(); i++) {
    if(gameList.get(i).getName().contains(query)) {
        temp.add(gameList.get(i));
    }
}
return temp;

You could also use a for-each loop like

for (GameStorage gs : gameList) {
    if (gs.getName().contains(query)) {
        temp.add(gs);
    }
}
return temp;

And in Java 8+ you might implement the entire method1 with a filter and Collectors

public static List<GameStorage> findElement(List<GameStorage> gameList, String query) {
    return gameList.stream().filter(x -> x.getName().contains(query))
            .collect(Collectors.toList());
}

1And I would prefer to program to the List interface.