How would I find an item in my linked list in java that matches another string or doesn't match the string?

StackOverflow https://stackoverflow.com/questions/19671735

Question

I have a custom generic linked list in java (it is not java's LinkedList or any of the collections). My linked list has a node, a ListInterface, the actual LinkedList, a class file and a file with the main method. This linked list and classes are supposed to form a DVD inventory manager. What I am trying to do is traverse the list and check to see if the string that the user has passed in is equal to the string of one of the variables of one of the objects in the linked list.

This is what I have so far:

    if (movies.isEmpty()) {
        movies.add(new Dvd(userMovie), movies.length()+1);
    } else if (!movies.isEmpty()) {
        for (int i = 1; i <= movies.length(); i++) {
            if (movies.get(i).getTitle().equals(userMovie)) {   
                movies.get(i).addCopy();
            } else if (!movies.get(i).getTitle().equals(userMovie)) {
                movies.add(new Dvd(userMovie), movies.length()+1);
            }
        }
    }

In English: if the movies linked list is empty, add the movie that has been passed in (userMovie). else if the movies linked list is not empty, check each item in the list to see if the movie that has been passed in already exists. If it already exists, add a copy to it. Else if the movie that has been passed in does not exist, add the movie to the list.

This all works except for the last part.

I add a movie when empty and get this:

 Star Wars 1 // one copy of star wars has been added

I then add the same movie again and the copies updates:

 Star Wars 2

I then try to add a different movie and it starts out at two copies instead of 1:

 Harry Potter 2

I then try to add that same movie again to see what happens and it gives me this:

Star Wars 1
Harry Potter 3
Harry Potter 2
Was it helpful?

Solution

the logic of the inner loop is not correct.

try this, you only want to add a new movie once, not once for every movie that does not match it's title.

if (movies.isEmpty()) {
    movies.add(new Dvd(userMovie), movies.length()+1);
} else if (!movies.isEmpty()) {
    boolean found = false;
    for (int i = 1; i <= movies.length(); i++) {
        if (movies.get(i).getTitle().equals(userMovie)) {   
            movies.get(i).addCopy();
            found = true;
        }
    }
    if (!found) {
        movies.add(new Dvd(userMovie), movies.length()+1);
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top