java 程序(在文本文档中)中计算的单词、字母和字符数量错误

Error with the amount of words, letters, and characters counted in a java program (in a text doc)

我打算计算文本文档中的单词、字母和字符。遗憾的是,我收到的输出不正确。好像少了一行,所以有几个字和词也不算在内。感谢帮助。

代码如下:

package assignments;

import java.io.*;

public class Assignment7 {

public static void main(String args[]) throws Exception {
    FileInputStream file = new FileInputStream(
            "C:/Users/Shashu/Desktop/Workspace/sample.txt");
    BufferedReader br = new BufferedReader(new InputStreamReader(file));
    int i;
    int countw = 0, countl = 0, countc = 0;
    do {
        i = br.read();
        if ((char) i == (' ')) { 
            countw++;
        }
        if ((char) i == ('\n')) { 
            countw++; 
            countl++;
        } 
        if (i != -1) {
            countc++; 
        }

    } while (i != -1);

    System.out.println("Number of words " + countw);
    System.out.println("Number of lines " + countl); 
    System.out.println("Number of characters " + countc);
}
}

这是文本文档:

hi my name is shashu
hello
hello
hello

这是输出:

Number of words 7
Number of lines 4
Number of characters 41

感谢所有的帮助和批评!提前致谢。 编辑:好的,我解决了这个问题,谢谢大家。但是,现在我该怎么做才能在命令提示符中选择文本文件?

例如:

java 作业 7 sample.txt

您的文本文档末尾没有换行符(实际上 Windows 中有两个字符),因此最后一个单词不算在内。

public static void main(String args[]) throws Exception {
    FileInputStream file = null;
    BufferedReader br = null;
    try {
        file = new FileInputStream(
                "C:/Users/Shashu/Desktop/Workspace/sample.txt");
        br = new BufferedReader(new InputStreamReader(file));

        int countw = 0, countl = 0, countc = 0;
        String line = null;
        while ((line = br.readLine()) != null) {
            countl++;
            String[] words = line.split(" ");
            for (String word : words) {
                word = word.trim();
                if (word.length() == 0) {
                    continue;
                }
                countw++;
                countc += word.length();
            }

        }
        System.out.println("Number of words " + countw);
        System.out.println("Number of lines " + countl);
        System.out.println("Number of characters " + countc);
    } finally {
        if (file != null) {
            file.close();
        }
    }

}