Solved

Count how many letters in the input file?

Posted on 2003-11-23
2
2,309 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
[X]
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
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

Technology Partners: 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

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…
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 scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
The viewer will learn how to implement Singleton Design Pattern in Java.

623 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