Solved

Count how many letters in the input file?

Posted on 2003-11-23
2
2,304 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
Comment Utility
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
Comment Utility
8-)
0

Featured Post

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

For customizing the look of your lightweight component and making it look lucid like it was made of glass. Or: how to make your component more Apple-ish ;) This tip assumes your component to be of rectangular shape and completely opaque. (COD…
Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
Viewers learn about the third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.

772 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

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now