首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >调用SLNode<E> find()方法

调用SLNode<E> find()方法
EN

Stack Overflow用户
提问于 2011-09-22 23:02:27
回答 1查看 289关注 0票数 0

我正在做一个学校的作业,其中提供了一个SinglyLinkedList类,我们应该创建一个程序,调用这个类来添加、删除、查找和显示列表中的项目。我已经很好地实现了add、delete和display方法,但是我不知道如何调用find方法。任何帮助都是最好的。

下面是我需要实现的SinglyLinked类中的方法:

代码语言:javascript
运行
复制
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

}

下面是我所拥有的……我还包含了其他方法的实现:

代码语言:javascript
运行
复制
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);
}

我肯定我会踢自己,因为这比我做的简单,但我真的被卡住了。

EN

回答 1

Stack Overflow用户

发布于 2011-09-22 23:17:40

您的列表显然包含宠物,由一些宠物类型(看起来像String)表示。所以find希望你在addPet中添加一个类似的宠物类型。并返回一个包含找到的宠物的SLNode。因为您还没有发布SLNode,所以我不知道如何获取其中包含的元素,但是在它上调用getElement()看起来像是一个安全的赌注:-)所以您需要检查find返回的值是否为null。如果它不是null,你可以获取其中包含的元素并打印出来。

我想这对你写代码应该足够了;如果不清楚,请评论。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7516998

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档