Count how many letters in the input file?

Posted on 2003-11-23
Last Modified: 2007-12-19
i tried to make a program to count lettres in  an input file and i need result like this(for example it depends on your file and the output must write the only letter in the file )
Letter  Frequency
A           3
V           4
M           2

but my reslut is
Letter  Frequency
A           2
B           2
C           2
........ els

it gives me the number of the first letter in my input file correctly and then write all the ltters whith the same number of the first letter. as i mention above i dont need all the letter i need just what is written in the file with correct frequency.
this is my code


public class Stats2

      public static void main(String[] args )
            if (args.length < 0)
            System.out.println("No filename specified");

                  FileReader reader = new FileReader("text.txt");
          catch (IOException ioe)
                  System.err.println(" Error on  opening file\n" + ioe.toString() );
                  char[] capital = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J','K', 'L', 'M', 'N',
                                    'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};

            char[] small =   { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
                                  'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' };
                  System.out.println("Leter     Frequency");
                  FileReader reader = new FileReader("text.txt");
                  int nextChar;
                  char ch;
                  int count=0;
            for (int i = 0; i < 26; i++)

      while ( (nextChar = ) != -1 )

      ch = (char) nextChar;
      if( ch== capital[i] || ch == small[i] )


              System.out.print("  " + capital[i]);
              System.out.println("          " + count);



            catch( IOException ioe)
                  System.err.println("Input/output error");
Question by:alqaoud
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
LVL 86

Accepted Solution

CEHJ earned 50 total points
ID: 9806220
You need to maintain a Map where the key is the letter and the value is the number of occurrences. Here is a version for words. Use the same principle for letters. Here you would need to create Character objects as keys

import java.util.*;

public class WordCount {
  private StreamTokenizer streamTokenizer;
  private TreeMap treeMap;
  private Reader reader;
  private Writer writer;

 class Counter {
   private int i;

   public Counter(int i) {
     this.i = i;
   public void increaseCount() {
   public String toString() {
     return Integer.toString(i);

 public WordCount(String fileName) {
   try {
     reader = new BufferedReader(new FileReader(fileName));
   catch (FileNotFoundException fnfe) {
   streamTokenizer = new StreamTokenizer(reader);

    // you can use this method to customize your needs

   treeMap = new TreeMap();
   try {
     while (streamTokenizer.nextToken() != StreamTokenizer.TT_EOF) {
       String s;
       switch (streamTokenizer.ttype) {
            case StreamTokenizer.TT_EOL :
              s = new String("EOL");
            case StreamTokenizer.TT_WORD :
               s = streamTokenizer.sval;
            case StreamTokenizer.TT_NUMBER :
              s = Double.toString(streamTokenizer.nval);
            default :
              s = String.valueOf((char)streamTokenizer.ttype);
       if (treeMap.containsKey(s))
         treeMap.put(s, new Counter(1));
    catch(IOException ioe) {
 public Set entrySet() {
   return treeMap.entrySet();

 public Iterator iterator() {
   return entrySet().iterator();

 public void printResult() {
   Iterator iterator = iterator();
   while (iterator.hasNext()){

 public static void main(String[] args) {
   if(args.length < 1){
     System.out.println("Usage: java WordCount <file>");
   new WordCount(args[0]).printResult();
LVL 86

Expert Comment

ID: 9809959

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
login jsp example 24 105
ejb example issues 3 90
jmeter usage 4 68
netbeans can not run self signed app 8 38
Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…
The viewer will learn how to implement Singleton Design Pattern in Java.
Suggested Courses

752 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question