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. 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);
}
}
You could also use this
while((sentence = reader.readLine()) != null) {
String[] wordlist = sentence.split("\\s+");
whitespaceCount += wordlist.length-1;
}