Link to home
Start Free TrialLog in
Avatar of chataholic4real
chataholic4real

asked on

creating an ouput file to store the results

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();
       
      }  
  }

}
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

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

https://www.experts-exchange.com/questions/20953776/help-need-quick-answer.html#10868811
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']++;
            }
Avatar of chataholic4real
chataholic4real

ASKER

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;

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
          }
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
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..
So do i take it that 'watu.txt' contains lines of text composed of capital letters?
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 ....
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();
      }      
}      
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
ASKER CERTIFIED SOLUTION
Avatar of Mick Barry
Mick Barry
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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..
try:

outFile.println((char)('A'+i)+" " + count[i]);
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]);
 }

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

u need to define the max variable:
      ...
      int[] count = new int[26];
      int max = 0;
       ...
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]);

                 
> 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.

Thanx alot again..I really appreciate..it..
No worries :)
Just as a by the way..how do you round off a no. e.g 1.23424 to 1.234?
Just as a by the way..how do you round off a no. e.g 1.23424 to 1.234?
use DecimalFormat:

import java.text.*;


float f = 1.23424;
DecimalFormat df = new DecimalFormat("0.000");
String s = df.format(f);
>>
..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

Also you should not mix the functionality of reading the source file and writing the result - they should be kept separate