开发者

Calling SLNode<E> find() method

I am working on an assignment for school where a SinglyLinkedList class is provided and we are supposed to create a program that makes calls to this class to add, delete, find, and display items in a list. I have implemented the add, delete and display methods just fine, but I can't figure out how to call the find method. Any help would be great.

Here is the method from the SinglyLinked Class which I need to imp开发者_高级运维lement:

private SLNode<E> find( E target ) {
SLNode<E> cursor = head.getSuccessor();

while ( cursor != tail ) {
  if ( cursor.getElement().equals( target ) ) {
    return cursor; // success
  }
  else {
    cursor = cursor.getSuccessor();
  }
}

return null; // failure

}

Here is what I have...I've included the implementations of the other methods as well:

public static void addPet()
{
    Scanner keyboard = new Scanner(System.in);      
    System.out.print("\nPlease enter your pet's name and what type of \n    animal it is(i.e. \"Mickey, Mouse\"): \n");
    petType = keyboard.nextLine();
    pet.add(petType, 0);
    System.out.printf("%s was added to the list.\n\n", petType);        
}

public static void displayPets()
{       
    int i;
    for(i=0; i<pet.getLength(); i++)
    {
        System.out.printf("\n%d.\t%s",i+1, pet.getElementAt(i));
    }
    System.out.print("\n\n");
}

public static void deletePet()
{
    int i;
    int j;
    int k;
    String a;
    for(i=0; i<pet.getLength(); i++)
    {
        System.out.printf("\t%d. %s\n",i+1, pet.getElementAt(i));
    }
    System.out.println();
    System.out.printf("\nPlease enter the number of the item to delete: \n");
    Scanner input = new Scanner(System.in);
    j = input.nextInt();
    System.out.printf("%s was deleted from the list.\n\n", pet.getElementAt(j-1));
    pet.remove(j-1);
}

public static void findPet()
{
    String keyword;
    Scanner keyboard = new Scanner(System.in);
    System.out.print("Please enter a search term: ");
    keyword = keyboard.nextLine();
    //.find(keyword);
}

I'm sure I will kick myself because it's simpler than I'm making it, but I'm really just stuck.


Your list apparently contains pets, represented by some pet type (which looks like a String). So find expects a similar pet type you added in addPet. And returns an SLNode containing the found pet, if there is one. Since you haven't posted SLNode, I can't tell how to get the element contained in it, but calling getElement() on it looks like a safe bet :-) So you need to check the value returned by find, for nullness. If it's not null, you can e.g. get the element contained in it and print it.

I suppose this should be enough for you to write the code; if it's not clear, please comment.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜