编辑

许多用户评论说Class Word是无用的,在这种情况下可能是正确的。之所以添加它,是因为稍后在程序中需要它。

该程序有3个类-WordList,Word和一个测试类。我试图获取方法'readBook'来读取文件,并将每个单词发送到方法'addWord'。方法addWord将检查ArrayList allWords是否包含该单词。如果没有,则addWord会将单词添加到数组,并将其发送到Word类。当我运行程序时,什么也没有发生。我试图打印出allWords.size(),该函数返回0。

类WordList:

public class WordList {

String nextWord;
ArrayList<String> allWords = new ArrayList<String>();

public void readBook (String filename) throws Exception{
    File file = new File(filename); //File has one word on each line.
    Scanner innFile = new Scanner(file);
    for (int i = 0; i<file.length(); i++){
        if(innFile.hasNextLine()){
            nextWord = innFile.nextLine();
            addWord(nextWord);
        }
    }
}
private void addWord(String word){
    for (String check : allWords){
        if (!check.equalsIgnoreCase(word)){
            allWords.add(word);
            new Word(word);
        }
        else if(check.equalsIgnoreCase(word)){
            System.out.println("The word allready exsist.");
        }
        else{
            System.out.println("Something went wrong.");
        }
    }
}


类词:

public class Word {

String word;
ArrayList<String> allWords = new ArrayList<String>();

Word(String text){
    word = text;
    allWords.add(word);
    System.out.print(allWords);

}


测试班:

public class TestClass {
public static void main (String[] args) throws Exception{
    WordList list = new WordList();
    list.readBook("path.../scarlet.text");

    WordList newList = new WordList();
    System.out.println(newList.numberOfWords());//A method printing out allWords.size()

    }
}

最佳答案

您正在allWords中填充WordList类的for (String check : allWords)列表。最初它是空的,因此它将永远不会进入for循环,并且allWords永远不会被填充。反过来,不会调用new Word(word),单词类的allWords将为空。

09-25 17:25