Advertisement
richarduie

FileLetterCounter

May 19th, 2013
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.73 KB | None | 0 0
  1. import java.io.BufferedReader;
  2. import java.io.File;
  3. import java.io.FileInputStream;
  4. import java.io.FileNotFoundException;
  5. import java.io.IOException;
  6. import java.io.InputStreamReader;
  7. import java.util.Scanner;
  8.  
  9. public class FileLetterCounter
  10. {
  11.     private static String ALPHAS = "abcdefghijklmnopqustuvwxyz";
  12.    
  13.     public static void main(String args[] ) {
  14.         // get name of input file from user
  15.         Scanner keyboard = new Scanner( System.in );
  16.         System.out.print( "Please enter the name of a file: " );
  17.         String nameOfFile = keyboard.next();
  18.    
  19.         // try to open file for reading
  20.         BufferedReader reader = null;
  21.         try {
  22.             reader = new BufferedReader(
  23.                 new InputStreamReader( new FileInputStream( new File( nameOfFile )))
  24.             );
  25.         } catch ( FileNotFoundException e ) {
  26.             System.out.println( "sorry - no such file as: " + nameOfFile );
  27.             return;
  28.         }
  29.        
  30.         String line;            // to capture each line of file
  31.         int[] counts = new int[26]; // to hold counts of letters (alphabetic characters)
  32.         try {
  33.             // for as long as there is content in the file...
  34.             while( null != (line = reader.readLine()) ) {
  35.                 counts = doCounts( line, counts);
  36.             }
  37.         } catch ( IOException e ) {
  38.             System.out.println( "sorry - error reading file: " + nameOfFile +
  39.                     "reported error was:\n\n" + e.toString() );
  40.             return;
  41.         }
  42.         print( counts );
  43.        
  44.     }
  45.     public static int[] doCounts( String line, int[] counts) {
  46.         for (int i = 0; i < ALPHAS.length(); i++) {
  47.             counts[ i ] += line.toLowerCase( ).replaceAll( "[^"+ ALPHAS.charAt( i ) +
  48.                 "]", "").length( );
  49.         }
  50.         return counts;
  51.     }
  52.     public static void print( int[] counts ) {
  53.         for (int i = 0; i < ALPHAS.length(); i++) {
  54.             System.out.println( ALPHAS.charAt( i ) + ": " + counts[ i ]);
  55.         }
  56.        
  57.     }
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement