gpt4 book ai didi

java - 计数器循环不工作

转载 作者:行者123 更新时间:2023-12-01 17:25:45 25 4
gpt4 key购买 nike

此方法旨在每次链接列表中的项目等于给定元素(在我的例子中为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。我检查了我的循环,但无法找出哪里出错了

最佳答案

在 for 循环中,您正在比较 Node<E>E 。他们永远不会平等。

关于java - 计数器循环不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15048720/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com