Home > front end >  Why does my not not read the blank lines I have fixed my issue about blank spaces and now this
Why does my not not read the blank lines I have fixed my issue about blank spaces and now this

Time:05-15

This is my code for reading a file and coding how may numbers, size and the current date.

package ME4;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

public class myFileHandle
{
   public static void main(String[] argvs) throws IOException 
   {
       
      //Number of Words Code
      File f1=new File("myInput");
      String[] words=null;
      int wc=0;   
      FileReader fr = new FileReader(f1);   
      BufferedReader br = new BufferedReader(fr);   
      String tmpStr;
      while((tmpStr=br.readLine())!=null)   
      {
         words=tmpStr.split("[ ] ");  
         for (String str : words) {
                if (str.strip().length() > 0) {
                    System.out.println("added: "   str);
                   wc = wc ;
                }
             }
         wc=wc words.length;   
      }
      
      //Time and Date Code
      long millis = System.currentTimeMillis();  
      java.util.Date date = new java.util.Date(millis);
      
      fr.close();
      
      //Size of the File Code
      long fileSize = f1.length();
      
      System.out.println("Number of words: "  wc);
      System.out.println(String.format("The size of the file: %d bytes", fileSize));
      System.out.println("Current Time: " date);
   }

}

This is the myInput code

Thorndike
Hull
Skinner
 Maslow
Herzberg
Adams     Locke
Nicholls
Ames
Dweck
Handy

Alderfer
Bandura

And this is the Output:

Number of words: 15
The size of the file: 111 bytes
Current Time: Sat May 14 15:10:58 SGT 2022

How can I change the number of the words to 13, as you can see with the sample text there is only 13 words but it reads the missing lines how would I fix this?

CodePudding user response:

inside the loop where you read the line

while((tmpStr=br.readLine())!=null)   
{
  words=tmpStr.split("[ ] ");  
  wc=wc words.length;   
}

check for empty line (use the logic of if line is empty continue, before setting the words)

CodePudding user response:

Check the length of every String. Use below code

words = tmpStr.split("[ ] ");
 // ADD check for string 
 for (String str : words) {
    if (str.length() > 0) {
       wc = wc   1;
    }
 }
  •  Tags:  
  • java
  • Related