Count letters in a file Learn programming Java


File Management


Count letters in a file


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)


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.out.print("Letter for count: ");
		String letter = new Scanner(; myfile; myfileBufferedReader = new;
		myfile = new;

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

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

		if (debug)
			new Scanner(;

Juan A. Ripoll - Systems Tutorials and Programming Courses ©  All rights reserved.  Legal Conditions.