Search code examples
javafilebufferedreader

How can I get java to tell me the correct amount of lines and words in a file?


I am learning how to create a program that reads a file in class. I can only get java to tell me the correct amount of words in the file and not the correct amount of lines. How can I get java to tell me the correct amount of lines and words in a file?

public class Reader { public static void main(String args[]) throws IOException {

BufferedReader demo = new BufferedReader(new FileReader("All.txt"));

Scanner file = new Scanner(demo);

int lineCount = 0;
int wordCount = 0;

//wordCounter

while(file.hasNextLine()) {
  String amount = file.nextLine();

  String[] txt = amount.split(" ");
  for(int i = 0; i < txt.length; i++){
    if(txt[i].contains(txt[i]))
    wordCount++;
  }
}
System.out.println("There are  " + wordCount + " words.");

//lineCounter -- this is where my issue lies

String line = demo.readLine();
while(line != null){
  lineCount++;
  line = demo.readLine();

}
System.out.println("There are " + lineCount + " lines.");

} }


Solution

  • You can use this:

    To count sentences split each line with either ., !, ?.

    To count words splitting with space will be enough.

    import java.io.*;
    
    public class File {
    
        public static void main(String[] args) throws IOException {
            
            BufferedReader demo = new BufferedReader(new FileReader("/home/asn/Desktop/All.txt"));
            
            int lineCount = 0;
            int wordCount = 0;
            String line;
    
            while((line=demo.readLine())!=null)  {
                String[] words = line.split(" ");
                String[] sen = line.split("\\.|\\!|\\?");  // this a a regex expression to split with ., !, and ?
    
                lineCount += sen.length;
                wordCount += words.length;
              }
              System.out.println("There are  " + wordCount + " words.");
              System.out.println("There are  " + lineCount + " lines.");
    
              demo.close();
        }
    }