dominicvautour
dominicvautour

Reputation: 57

Searching a Java LinkedList

I am trying to search through a Java LinkedList that uses a custom object called Name. I need to search on first name (My compareTo method in Name already compares last names because I need to use it to sort by last name). Name has an observer method called getFirstName().

I am not having any success in accessing first name from my LinkedList. This is what I want to do but this (obviously) doesn't work.

if (iterator.next().getFirstName().equals(inputSearch))

Can someone point me in the right direction?

This is the full method I am currently trying to write:

// Creating a method to search for a first name
  static void searchName()
{
  Scanner inData = new Scanner(System.in);

  // Label to request input from user
  System.out.println("Enter the first name that you would like to search for:");

  // Setting variable to capture input
  String inputSearch = inData.next();

  // Creating an iterator to search through the list
  iterator = list.iterator(); 

  // While loop to search each entry
  while (iterator.hasNext())
  {
      if (iterator.next().getFirstName().equals(inputSearch))
      {
          System.out.println("MATCH FOUND: " + iterator.next());
      }
  }
} 

Upvotes: 0

Views: 351

Answers (2)

Jim Garrison
Jim Garrison

Reputation: 86774

You're calling iterator.next() twice. The second time will advance past the item you want. Instead, save the return value from the first call to iterator.next() and use that.

  while (iterator.hasNext())
  {
      Name item = (Name) iterator.next();

      if (item.getFirstName().equals(inputSearch))
      {
          System.out.println("MATCH FOUND: " + item);
      }
  }

or, more idiomatically

  for (Name item : list)
  {
      if (item.getFirstName().equals...
  }

Upvotes: 2

Jimmy
Jimmy

Reputation: 2619

while (iterator.hasNext())  {  
   if (iterator.next().getFirstName().equals(inputSearch)) {  //iterator.next()          
                   System.out.println("MATCH FOUND: " + iterator.next());  //iterator.next()     
     }   
 } 

Since you are calling next() twice, while printing it would be next object.

try storing whatever iterator.next() returns in its corresponding type and use it to compare and print if succeed.

ex:

while(iterator.hasNext(){
   Name name=iterator.next();
  if(name.getFirstName().equals(inputSearch)){
      System.out.println("Match Found"+name);
     }
}

This is what I see wrong. Not aware of anything else.

Upvotes: 2

Related Questions