Solved

creating an ouput file to store the results

Posted on 2004-04-20
26
332 Views
Last Modified: 2010-03-31
I was trying....this.. instead of displaying the results on the window got from counting letters (ie. a =10) from a particular text file, i wanted to store the results in an output file. Then normalise it by dividing by the highest no. got e.g if a=10 and b=12, then i would divide both values by 12. But first, my main issue is store the results. I have been trying but the result im getting is only for A=10, nothing else. Could someone help on this pliz...? the code is below..

import java.io.*;

public class BufferedReaderTest
{
 
  public static void main(String args[]) throws Exception
  {
    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'};
     
      FileReader fr = new FileReader("watu.txt");
      BufferedReader buffer = new BufferedReader(fr);
     
      String inString;
     
       FileWriter fw = new FileWriter("sorted.txt");
        BufferedWriter bw = new BufferedWriter(fw);
         PrintWriter outFile = new PrintWriter(bw);
      StringBuffer completeText = new StringBuffer();
     
      while ((inString = buffer.readLine()) !=null)
      {
        String upperCase = inString.toUpperCase();
        System.out.println(upperCase);
        completeText.append(upperCase);
      }
     
       
      char ch;
      int count=0;
        for (int i = 0; i < capital.length; i++)
         {
       
        //outFile.print(" " + capital[i]);
         
        count = 0;
     
       
       
       
        for (int j = 0; j<completeText.length(); j++)
        {  
         
          ch = completeText.charAt(j) ;
          if( ch== capital[i])
          {  
           
            count++;
           
            }
           
         
           
         
       }
         
        outFile.print(" " + count);
       
        outFile.close();
        fr.close();
       
      }  
  }

}
0
Comment
Question by:chataholic4real
  • 9
  • 8
  • 8
  • +1
26 Comments
 
LVL 86

Expert Comment

by:CEHJ
ID: 10869729
You need to build a histogram or table of frequencies, which you can save to a file. See the Histogram class in this question:

http://www.experts-exchange.com/Programming/Programming_Languages/Java/Q_20953776.html#10868811
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 10869781
In your case you could do something more like:

            int[] frequencies = new int[26];
            //all capital letters


            for (int i = 0; i < lineReadFromFile.length(); i++) {
                  char c = lineReadFromFile.charAt(i);
                  frequencies[c - 'A']++;
            }
0
 

Author Comment

by:chataholic4real
ID: 10870135
which point should i insert your code...and
// all capital letters..(in your  code.)..does this mean
  should insert all capital in the form of ...
   frequencies[0] = A;

0
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!

 
LVL 86

Expert Comment

by:CEHJ
ID: 10870193
Do you understand what my example does? I'm asking as maybe i haven't understood you correctly ;-) I'll comment it:

int[] frequencies = new int[26]; // a frequency table for occurrences of all capital letters


          for (int i = 0; i < lineReadFromFile.length(); i++) { // read the file line
               char c = lineReadFromFile.charAt(i); // separate the line into constituent capitals
               frequencies[c - 'A']++; // increment the table at the slot holding the frequency of the letter read
          }
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 10870328
i.e. i am assuming you have a file and you want to count the frequencies of capital letters therein. The frequency table should be created at the beginning of the program. The loop goes inside the loop that reads each line of the file
0
 

Author Comment

by:chataholic4real
ID: 10870466
i have the file which i want to count the frequencies..(look at the main code.) At the moment i think im not jus gettin your point. I would prefer if u would edit the main code with ur changes..( that would make sense abit..)..coz now im abit lost..
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 10870638
So do i take it that 'watu.txt' contains lines of text composed of capital letters?
0
 

Author Comment

by:chataholic4real
ID: 10872612
Yeh it does..it does contain...text made of small and capital letters..in my code,i got the code to convert everything to capital letters ....
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 10872703
This is basically it. All you need is a method to print 'frequencies' (which i'll let you write), plus main:


public class Frequencies {
      private static int NUMBER_OF_CHARACTERS = 26;
      private int[] frequencies;
      
      public Frequencies() {
             frequencies = new int[NUMBER_OF_CHARACTERS]; // a frequency table for occurrences of all capital letters
      }

      public void process(String fileName) throws IOException {
            BufferedReader in = new BufferedReader(new FileReader(fileName));
            String lineReadFromFile = null;
            while ((lineReadFromFile = in.readLine()) != null) {
                  for (int i = 0; i < lineReadFromFile.length(); i++) { // read the file line
                        char c = lineReadFromFile.charAt(i); // separate the line into constituent capitals
                        if (c >= 'A' && c <= 'Z') {
                              frequencies[c - 'A']++; // increment the table at the slot holding the frequency of the letter read
                        }
                  }
            }
            in.close();
      }      
}      
0
 

Author Comment

by:chataholic4real
ID: 10873800
thanx again..i was trying to run the  prog. and the following thing came up..could you tell me what it means..(explanation)
 Exception in thread "main" java. lang.NoSuchMethodError:main
0
 
LVL 92

Accepted Solution

by:
objects earned 40 total points
ID: 10873908
try something like this:

import java.io.*;

public class BufferedReaderTest
{
 
  public static void main(String args[]) throws Exception
  {
      int[] count = new int[26];
     
      FileReader fr = new FileReader("watu.txt");
      BufferedReader buffer = new BufferedReader(fr);
     
      String inString;
     
       FileWriter fw = new FileWriter("sorted.txt");
        BufferedWriter bw = new BufferedWriter(fw);
         PrintWriter outFile = new PrintWriter(bw);
      StringBuffer completeText = new StringBuffer();
     
      while ((inString = buffer.readLine()) !=null)
      {
        String upperCase = inString.toUpperCase();
        char[] ch = upperCase.toCharArray();
        for (int i =0; i<ch.length; i++)
        {
              int index = ch[i] - 'A';
              if (index>=0 && index<count.length) count[index]++;
        }
      }
     
       
      for (int i = 0; i < count.length; i++)
      {
        outFile.println(('A'+i)+" " + count[i]);
      }
         
       
        outFile.close();
        fr.close();

  }

}
0
 

Author Comment

by:chataholic4real
ID: 10873961
hey..its workin..thanx..is there a way to convert the ascii codes to letters..since the letters in the output file are in ascii..codes. i was also thinking of normalising..the results by dividing them using the highest value ie. if  B=20, .. was the highest.. i would divide every other value with it ..so as to be able to plot a histogram..
0
 
LVL 92

Expert Comment

by:objects
ID: 10873976
try:

outFile.println((char)('A'+i)+" " + count[i]);
0
 
LVL 92

Expert Comment

by:objects
ID: 10873986
to normalize use:
outFile.println((char)('A'+i)+" " + (count[i]/(float)max));

and modify your counting loop to track the max:

 if (index>=0 && index<count.length)
 {
      count[index]++;
      max = Max.max(max, count[index]);
 }

0
 

Author Comment

by:chataholic4real
ID: 10874051
The following errors are coming up..what could be the prob..?

BufferedReaderTest.java:30: cannot resolve symbol
symbol  : variable max
location: class BufferedReaderTest
                 max = Max.max(max,count[index]);
                 ^
BufferedReaderTest.java:30: cannot resolve symbol
symbol  : variable max
location: class BufferedReaderTest
                 max = Max.max(max,count[index]);
                               ^
BufferedReaderTest.java:30: cannot resolve symbol
symbol  : variable Max
location: class BufferedReaderTest
                 max = Max.max(max,count[index]);
                       ^
BufferedReaderTest.java:38: cannot resolve symbol
symbol  : variable max
location: class BufferedReaderTest
        outFile.println((char)('A'+i)+" " + (count[i]/(float)max));
                                                             ^
4 errors

0
 
LVL 92

Expert Comment

by:objects
ID: 10874070
u need to define the max variable:
      ...
      int[] count = new int[26];
      int max = 0;
       ...
0
 

Author Comment

by:chataholic4real
ID: 10874165
3 errors have disappeared..only 1 remaining..and also could you explain to me(comment)..what the line means..thanx again
BufferedReaderTest.java:31: cannot resolve symbol
symbol  : variable Max
location: class BufferedReaderTest
                 max = Max.max(max,count[index]);
                           ^
1.     outFile.println((char)('A'+i)+" " + (count[i]/(float)max));
2.  max = Max.max(max, count[index]);

                 
0
 
LVL 92

Expert Comment

by:objects
ID: 10874311
> max = Max.max(max,count[index]);

woops that should be:

max = Math.max(max,count[index]);

max is a method in the Math class that returns the maximum of two numbers.

0
 

Author Comment

by:chataholic4real
ID: 10874357
Thanx alot again..I really appreciate..it..
0
 
LVL 92

Expert Comment

by:objects
ID: 10874376
No worries :)
0
 

Expert Comment

by:kenyapeke
ID: 10874831
Just as a by the way..how do you round off a no. e.g 1.23424 to 1.234?
0
 

Author Comment

by:chataholic4real
ID: 10874852
Just as a by the way..how do you round off a no. e.g 1.23424 to 1.234?
0
 
LVL 92

Expert Comment

by:objects
ID: 10874867
use DecimalFormat:

import java.text.*;


float f = 1.23424;
DecimalFormat df = new DecimalFormat("0.000");
String s = df.format(f);
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 10876629
>>
..could you tell me what it means..(explanation)
 Exception in thread "main" java. lang.NoSuchMethodError:main
>>

You had no main method. See my comment above (with added emphasis):

>>All you need is a method to print 'frequencies' (which i'll let you write), PLUS MAIN

0
 
LVL 86

Expert Comment

by:CEHJ
ID: 10876735
Also you should not mix the functionality of reading the source file and writing the result - they should be kept separate
0
 
LVL 92

Expert Comment

by:objects
ID: 10904721
:)
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

Suggested Solutions

Title # Comments Views Activity
Weekend adv creator 3 64
eclipse buid path vs tomcat lib path 10 37
running on tomcat not jboss eap 7.0 3 28
Java 8 to Java 6 8 32
Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
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 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…
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…

679 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