java程序(在文本文档中)中计算的单词、字母和字符数量错误
我打算数一数文本文档中的单词、字母和字符。遗憾的是,我一直收到的输出是不正确的。似乎有一行被删掉了,因此一些字符和单词也没有被计算在内。谢谢你的帮助 代码如下:java程序(在文本文档中)中计算的单词、字母和字符数量错误,java,text,document,Java,Text,Document,我打算数一数文本文档中的单词、字母和字符。遗憾的是,我一直收到的输出是不正确的。似乎有一行被删掉了,因此一些字符和单词也没有被计算在内。谢谢你的帮助 代码如下: package assignments; import java.io.*; public class Assignment7 { public static void main(String args[]) throws Exception { FileInputStream file = new FileInputSt
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 Assignment7 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();
}
}
}