Count letters in a file Learn programming Java

Lesson:

File Management


Exercise:

Count letters in a file 38


Objetive:

Create a program to count the amount of times that a certain character is inside a file (of any kind).

The file and the letter can be asked to the user or passed as parameters:

count example.txt a

It must display in screen the amount of letters found.

(you can choose any way to interact with the user, showing the proper help)


Code:

package Counterletters;
import java.util.*;

public class Main
{
	public static void main(String[] args)
	{
		boolean debug = true;

		System.out.print("Name of file: ");
		String nameFile = new Scanner(System.in).nextLine();
		System.out.print("Letter for count: ");
		String letter = new Scanner(System.in).nextLine();

		java.io.FileReader myfile;
	    java.io.BufferedReader myfileBufferedReader = new java.io.BufferedReader(myfile);
		myfile = new java.io.FileReader(nameFile);

		String line;
		int countLetter = 0;
		do
		{
			line = myfileBufferedReader.readLine();
			if (line != null)
			{
				for (int i = 0; i < line.length(); i++)
				{
					if (line.substring(i, i + 1).equals(letter))
					{
						countLetter++;
					}
				}
			}
		} while (line != null);
		myfile.close();

		System.out.printf("Amount of letter: %1$s" + "\r\n", countLetter);

		if (debug)
		{
			new Scanner(System.in).nextLine();
		}
	}
}