Word Count and Line Count Program in java

 /*  
 WordCount.java: In this program we will see how to read file using Scanner.   
 Author:itsafiz@gmail.com  
 */  
 import java.io.*;  
 import java.util.*;  
 class WordCount {  
   public static void main(String[] unused) {  
     Scanner in = new Scanner(System.in); // scanner object.   
      int words=0,lines=0;   
      try{  System.out.println("Enter Your file name");  
           File inputFile = new File(in.nextLine()); // reading file   
           Scanner wordScanner = new Scanner(inputFile);   
           Scanner lineScanner = new Scanner(inputFile);  
          wordScanner.useDelimiter("[^A-Za-z]+"); //   
           while(wordScanner.hasNext())  
                {  
                wordScanner.next(); // return next word if presents.   
                words++;   
                }  
           while(lineScanner.hasNextLine())// return boolean if line presents.  
                {  
                     lineScanner.nextLine(); // return next line if presents.   
                     lines++;   
                }  
           System.out.println("Total Words = "+words+"\nTotal line = "+lines);  
        }catch(IOException e)  
           {  
                System.out.println(e);  
           }  
      }  
 }  

Post a Comment

0 Comments