简体   繁体   English

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

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

I am trying to write a code that reads a file and puts all the words on a String array and then it prints all the array as a column. 我正在尝试编写一个读取文件的代码,并将所有单词放在String数组上,然后将所有数组打印为一列。 I wrote a code that should work but instead of getting the words printed, I get only "null" all the time. 我写了一个应该起作用的代码,但始终没有显示出来,而是一直只有“ null”。

The problem must be on the: word[totalWords] = read.inWord(); 问题必须在以下位置: word[totalWords] = read.inWord();

What do you recommend me to write instead, to get the words correctly stored? 您建议我写些什么,以正确存储单词?

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]);
    }
}

You are printing the element at the index after the one you've modified which hasn't been initialized yet, ie. 在修改完尚未初始化的索引之后,即在索引处打印元素,即。 is null . null Flip your logic 翻转逻辑

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

You are printing the word a bit late. 您将单词打印得晚了一点。 It should be: 它应该是:

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

ie you should first print the word and then increment the counter. 也就是说,您应该先打印单词,然后增加计数器。 In your case you are trying to print the value of the unassigned array element, hence you get null . 在您的情况下,您尝试打印未分配的数组元素的值,因此得到null

More beautiful way would be : 更漂亮的方式是:

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

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

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