繁体   English   中英

Java:如何将文本文件中的所有单词保存在String数组上

[英]Java: how to save all the words from a text file on a String array

我正在尝试编写一个读取文件的代码,并将所有单词放在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++;

您将单词打印得晚了一点。 它应该是:

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

也就是说,您应该先打印单词,然后增加计数器。 在您的情况下,您尝试打印未分配的数组元素的值,因此得到null

更漂亮的方式是:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM