Java 方法只是停止运行

Cro*_*mpy 1 java

我正在运行一种相当直接的方法,它按字母顺序将单词添加到列表中。

出于某种原因,每当“addToData”方法结束时,它不会返回到主方法中的原始调用者,而是一起停止。

我已经调试了代码,它没有进入任何无限循环,也没有遇到异常。

主要方法:

// Create the first list, with empty constructor
    TextList list0 = new TextList();
    
    // Check the method - addToData 
    System.out.println(list0);  
    list0.addToData("hello");
    System.out.println("list0 after adding the word hello: \n"+list0); 
    list0.addToData("hello");
    System.out.println("list0 after adding the word hello twice: \n"+list0); 
Run Code Online (Sandbox Code Playgroud)

我陷入困境的方法:

public void addToData(String word){//   O(n) -> Because we are going over the whole list only once (n times)
    if("".equals(word))
        return;
    if(_head == null) {
        _head = new WordNode(word);
        return;
    }
    WordNode temp = _head;
    int n = 0;
    WordNode ptr = temp.getNext();
    //pointer to the next word, and test on it so we'll always have a pointer to the previous word
    while(temp.getNext() != null){
        n = ptr.getWord().compareTo(word);
        if(n <= 0){
            temp.setNext(new WordNode(word));
            temp.getNext().setNext(ptr);
            return;
        }
        else {temp = ptr;
            ptr = ptr.getNext();
        }
    }
    temp.setNext(new WordNode(word));//if we went through the whole list, that means the word is the largest and comes last
}
Run Code Online (Sandbox Code Playgroud)

唯一打印到控制台的内容:

添加单词 hello 后的 list0:hello 1

由于多个问题,您可以在此处找到整个项目代码

我正在使用 IntelliJ,以防它可能与问题有关...

任何和所有建议都将不胜感激,因为我似乎无法找到有关此问题的任何内容。

Sma*_*ker 5

你的问题在 TextList.toString()

public String toString(){
    if(_head == null)
        return "";
    WordNode temp = _head;
    int counter = 1;
    String word = temp.getWord() + "\t";
    while(temp.getNext() != null){
        if(temp.getWord().equals(temp.getNext().getWord()))
        counter++;
        else {
        word = word + counter + "\n";
        if(temp.getNext() != null)
            word = word + temp.getNext().getWord() + "\t";
        }
    }
    word = word + counter;
    return word;
}
Run Code Online (Sandbox Code Playgroud)

如果代码曾经进入while循环,它就没有办法退出它。你永远不会改变任何一个temp或它的next值,这意味着while每次总是比较相同的值,从而创建一个无限循环。