【问题标题】:Calling SLNode<E> find() method调用 SLNode<E> find() 方法
【发布时间】:2011-09-22 15:02:27
【问题描述】:

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

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

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

}

这就是我所拥有的...我还包括了其他方法的实现:

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);
}

我确信我会踢自己,因为它比我做的简单,但我真的只是卡住了。

【问题讨论】:

  • @samack,他已经发布了他到目前为止所获得的内容。
  • pet变量的类型是什么? SinglyLinked 什么? SinglyLinked&lt;String&gt;?
  • 是的,字符串。对此感到抱歉。

标签: java singly-linked-list


【解决方案1】:

您的列表显然包含宠物,由某种宠物类型表示(看起来像 String)。所以find 期待您在addPet 中添加的类似宠物类型。并返回一个包含找到的宠物的SLNode(如果有的话)。由于您还没有发布SLNode,我不知道如何获取其中包含的元素,但是在它上面调用getElement() 看起来是一个安全的选择:-) 所以您需要检查@987654327 返回的值@,代表nullness。如果不是null,你可以例如获取其中包含的元素并打印出来。

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

【讨论】:

  • SLNode 没有提供给我们。
  • @Brandon,好的,那么我想练习的重点只是检查有问题的项目是否存在于列表中。换句话说,您应该打印一条消息,例如“找到!”如果find 返回的值不为空,并且“未找到!”如果为空。
  • 我试图调用 pet.getElement(keyword),但它只是说: Pet.java:73: cannot find symbol symbol : method getElement(java.lang.String) location: class gray.adts .ch3.SinglyLinkedList pet.getElement(keyword);
  • 我仍然不确定如何实际调用 find 方法,甚至返回 true 或 false。有什么想法吗?
  • @Brandon,好吧,我想我知道为什么了。您上面显示的find 方法是private,因此不能从外部SinglyLinkedList 调用。您确定这是您需要使用的方法吗?该类中是否还有其他名称相似但 public 限定符的方法?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-10
  • 1970-01-01
  • 1970-01-01
  • 2021-03-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多