Solved

Count how many letters in the input file?

Posted on 2003-11-23
2
2,307 Views
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

import java.io.FileReader;
import java.io.IOException;

public class Stats2
{

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

                  FileReader reader = new FileReader("text.txt");
          }
          catch (IOException ioe)
          {
                  System.err.println(" Error on  opening file text.data\n" + ioe.toString() );
                  System.exit(1);
          }
          try
          {
                  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 = reader.read() ) != -1 )
      {

      ch = (char) nextChar;
      if( ch== capital[i] || ch == small[i] )
      {
       count++;
                }

      }

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

             }

                  reader.close();

                  System.exit(0);
            }
            catch( IOException ioe)
            {
                  System.err.println("Input/output error");
                  System.exit(2);
            }
      }
}
0
Comment
Question by:alqaoud
  • 2
2 Comments
 
LVL 86

Accepted Solution

by:
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.*;
import java.io.*;

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() {
     i++;
   }
   public String toString() {
     return Integer.toString(i);
   }
 }

 public WordCount(String fileName) {
   try {
     reader = new BufferedReader(new FileReader(fileName));
   }
   catch (FileNotFoundException fnfe) {
     System.out.println(fnfe.toString());
   }
   streamTokenizer = new StreamTokenizer(reader);

    // you can use this method to customize your needs
   streamTokenizer.ordinaryChar('.');

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

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

 public void printResult() {
   Iterator iterator = iterator();
   while (iterator.hasNext()){
     System.out.println(iterator.next().toString());
   }
 }

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

Expert Comment

by:CEHJ
ID: 9809959
8-)
0

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

After being asked a question last year, I went into one of my moods where I did some research and code just for the fun and learning of it all.  Subsequently, from this journey, I put together this article on "Range Searching Using Visual Basic.NET …
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
The viewer will learn how to implement Singleton Design Pattern in Java.

820 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