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());
}
}
}
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 toiterator.next()and use that.or, more idiomatically