Solved

Count how many letters in the input file?

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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.

929 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

13 Experts available now in Live!

Get 1:1 Help Now