[英]Can someone help me figure out what is wrong with my WhiteSpaceCounter code?
I need a program that counts the whitespace in a text document, but it keeps giving me an insane number of whitespaces, as I think the while loop just keeps repeating.我需要一个程序来计算文本文档中的空格,但它总是给我大量的空格,因为我认为 while 循环只是不断重复。 could anyone read it over and tell me what is up?任何人都可以阅读并告诉我发生了什么事吗?
import java.io.*;
public class WhiteSpaceCounter {
public static void main(String[] args) throws IOException {
File file = new File("excerpt.txt");
FileInputStream fis = new FileInputStream(file);
InputStreamReader inreader = new InputStreamReader(fis);
BufferedReader reader = new BufferedReader(inreader);
String sentence;
int countWords = 0, whitespaceCount = 0;
while((sentence = reader.readLine()) != null) {
String[] wordlist = sentence.split("\\s+");
countWords += wordlist.length;
whitespaceCount += countWords -1;
}
System.out.println("The total number of whitespaces in the file is: "
+ whitespaceCount);
}
} }
If you first line has 3 word and your second line has 10 words, then you logic is如果您的第一行有 3 个单词,而您的第二行有 10 个单词,那么您的逻辑是
countWords (0) += 3 -> 3
countWords(3) += 10 -> 13
So do not use +=所以不要使用 +=
countWords = wordlist.length;
You could also use this你也可以用这个
while((sentence = reader.readLine()) != null) {
String[] wordlist = sentence.split("\\s+");
whitespaceCount += wordlist.length-1;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.