Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/361.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java:增加从文件存储到数组中的每个单词的字数_Java - Fatal编程技术网

Java:增加从文件存储到数组中的每个单词的字数

Java:增加从文件存储到数组中的每个单词的字数,java,Java,我试图读取一个文件并将文件中的单词存储到字符串数组中,不包括空格/多个空格。例如,我的文件中有“this is a test”字样,程序应存储在数组arr[“this”、“is”、“a”、“test”]中,并在每次将单词存储到数组中时增加一个名为wordCount的变量 我知道我可以使用 fileContents.split("\\s+") 但这不会在每次向数组中添加单词时增加字数。我想一个for循环可以完成这项工作,但我不知道怎么做 感谢您的帮助。谢谢 BufferedReader read

我试图读取一个文件并将文件中的单词存储到字符串数组中,不包括空格/多个空格。例如,我的文件中有“this is a test”字样,程序应存储在数组arr[“this”、“is”、“a”、“test”]中,并在每次将单词存储到数组中时增加一个名为wordCount的变量

我知道我可以使用

fileContents.split("\\s+")
但这不会在每次向数组中添加单词时增加字数。我想一个for循环可以完成这项工作,但我不知道怎么做

感谢您的帮助。谢谢

BufferedReader reader;
    try {
        reader = new BufferedReader(new FileReader(
                "/Users/pankaj/Downloads/myfile.txt"));
        String line = reader.readLine();
        int count = 0;
        while (line != null) {
            String[] array = line.split("\\s+");
            count = count + array.length;
            line = reader.readLine();
        }
        reader.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

在这里,我一行一行地获取,这样您就可以在每行中添加额外的功能。还可以按count变量获取count。

您可以迭代分割调用的结果,并在同一迭代中将一个结果添加到单词count中:

        String fileContents = "this is a test";
        int wordCount = 0;
        for (String word: fileContents.split("\\s+")) {
            System.out.println(word);
            wordCount++;
            System.out.println(wordCount);
        }
每次有新词时,都应该在数组结构中添加存储