0

此方法旨在每次 a 中的项目linked list等于给定元素(在我的情况下为 elem)时添加到计数器。

我有;

public int count(E elem) {
    Node <E> current = new Node <E>();
    current = head;
    int counter = 0;

    if (current == null) {
        return 0; //current is null
    }

    for (int i = 0; i<size; i++){
            if (elem == current){
                counter++;
                head = current.getNext();
            }
    }
    return counter;
    }



public static void main(String[] args) {

    SLinkedListExtended<String> x = new SLinkedListExtended<String>();

    x.insertAtTail("abc");
    x.insertAtTail("def");
    x.insertAtTail("def");
    x.insertAtTail("xyz");
    System.out.println(x.count("def")); // should print "2"
    x.insertAtTail(null);
    x.insertAtTail("def");
    x.insertAtTail(null);
    System.out.println(x.count("def")); // should print "3"
    System.out.println(x.count(null)); // should print "2"
}
}

但是在运行时,它每次都返回 0。我查看了我的循环,无法弄清楚我哪里出错了

4

2 回答 2

3

在您的 for 循环中,您将 a 与 a 进行Node<E>比较E。他们永远不会平等。

于 2013-02-24T04:43:08.537 回答
2

三个问题:

  1. elem == currentelem 是 E 类型, current 是 Node 类型。他们不会平等。您大概想要类似current.getElement().
  2. 您应该使用.equals()该比较,例如elem.equals(current.getElement()). 请注意,即使没有这个,您的测试也可能会起作用,但这只是因为您正在检查字符串并且它们是一种特殊情况(查找字符串实习)
  3. 您的循环没有在列表中移动。你有head = current.getNext();你想要的current = current.getNext()
于 2013-02-24T04:48:36.510 回答