Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.BufferedReader;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileNotFoundException;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.util.Scanner;
- public class FileLetterCounter
- {
- private static String ALPHAS = "abcdefghijklmnopqustuvwxyz";
- public static void main(String args[] ) {
- // get name of input file from user
- Scanner keyboard = new Scanner( System.in );
- System.out.print( "Please enter the name of a file: " );
- String nameOfFile = keyboard.next();
- // try to open file for reading
- BufferedReader reader = null;
- try {
- reader = new BufferedReader(
- new InputStreamReader( new FileInputStream( new File( nameOfFile )))
- );
- } catch ( FileNotFoundException e ) {
- System.out.println( "sorry - no such file as: " + nameOfFile );
- return;
- }
- String line; // to capture each line of file
- int[] counts = new int[26]; // to hold counts of letters (alphabetic characters)
- try {
- // for as long as there is content in the file...
- while( null != (line = reader.readLine()) ) {
- counts = doCounts( line, counts);
- }
- } catch ( IOException e ) {
- System.out.println( "sorry - error reading file: " + nameOfFile +
- "reported error was:\n\n" + e.toString() );
- return;
- }
- print( counts );
- }
- public static int[] doCounts( String line, int[] counts) {
- for (int i = 0; i < ALPHAS.length(); i++) {
- counts[ i ] += line.toLowerCase( ).replaceAll( "[^"+ ALPHAS.charAt( i ) +
- "]", "").length( );
- }
- return counts;
- }
- public static void print( int[] counts ) {
- for (int i = 0; i < ALPHAS.length(); i++) {
- System.out.println( ALPHAS.charAt( i ) + ": " + counts[ i ]);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement