Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

Count how many letters in the input file?

Posted on 2003-11-23
2
Medium Priority
?
2,312 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 150 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: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say 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

INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
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…
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:
Suggested Courses

783 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