我正在尝试编写一个代码,该文件读取一个文件并将所有单词放在String数组上,然后将所有数组打印为一列。我写了一个应该起作用的代码,但始终没有显示出来,而是一直只有“ null”。

该问题必须存在于:word[totalWords] = read.inWord();

您建议我写些什么,以正确存储单词?

public static void main(String[] args){

    In read = new In (args[0]);

    int totalWords = 0;

    String word[] = new String[31000];
    int uniqueWords[] = new int[31000];

    while(read.endOfFile() == false) {

        word[totalWords] = read.inWord();
        totalWords++;
        System.out.println(word[totalWords]);
    }
}

最佳答案

您正在修改的索引(尚未初始化)之后在索引处打印元素。是null。翻转逻辑

word[totalWords] = read.inWord();
System.out.println(word[totalWords]);
totalWords++;

10-05 23:36