0

For the assignment we're suppose to add a findFirst, findNext, and addElement method to the given class and test them. I manage to get the findNext and addElement working but not the findFirst.

Here's what the findFirst suppose to do
"Method findFirst(T item) searches for and returns the index of the element closest to the head node or returns -1 (not found)."

Here's my code

public int findFirst(T elem)
    {
        int retval = -1;//return a -1 if not found
        Node tmp = head;

        if(hasNext())
        {
            for (int k = 0; k < size; k++)
            {
                if (tmp.data.equals(elem))
                {
                    return retval = k;//return index closest to head
                }
                tmp = tmp.getNext();//going from head to tail
            }
        }
        return retval;
    }

No matter what I test, it would always return -1.

Thanks

Edited by cecsFTL

3
Contributors
4
Replies
5
Views
6 Years
Discussion Span
Last Post by NormR1
0

Try debugging the code by adding some println statements that show where the code is executing and the values of the variables as they change and are used. The output will show what the computer is seeing and what the code is doing.

0

Thanks for the input guys. Would that mean my findNext method is wrong too ? I did not use the parameter T for anything in findNext also. It is some what similar to findFirst, but it works.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.