我正在做一个实验报告,分配是"写一个名为countWord
的方法。它接收String
并返回输入String
的次数
在LinkedList
中找到。"
这是我的代码,但是当我运行它时,没有输出。
public class LinkedList {
private Node head; // the 'front' or 'head' node of the linked list
private int count;
public LinkedList() {
head = null;
count = 0;
}
// Method #1
public void addToFront(String d) {
Node n = new Node(d, head);
head = n;
count++;
}
//代码的其余部分..
public int countWord (String d) {
Node curr = head;
int index = 0;
while(curr != null) {
if(curr.getData().equals(d))
index++;
curr = curr.getNext();
}
}
return index;
}
演示类
public class Demo {
public static void main(String[]args){
LinkedList songs=new LinkedList();
songs.addToFront("blue");
songs.addToFront("crooked");
songs.addToFront("lie");
songs.addToFront("blue");
songs.addToFront("sober");
songs.addToFront("asdf");
songs.addToFront("blue");
System.out.println(songs.countWord("blue"));
}
}