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

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 356
  • Last Modified:

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

}
0
chataholic4real
Asked:
chataholic4real
  • 9
  • 8
  • 8
  • +1
1 Solution
 
CEHJCommented:
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
 
CEHJCommented:
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
 
chataholic4realAuthor Commented:
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
Independent Software Vendors: 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!

 
CEHJCommented:
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
 
CEHJCommented:
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
 
chataholic4realAuthor Commented:
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
 
CEHJCommented:
So do i take it that 'watu.txt' contains lines of text composed of capital letters?
0
 
chataholic4realAuthor Commented:
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
 
CEHJCommented:
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
 
chataholic4realAuthor Commented:
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
 
objectsCommented:
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
 
chataholic4realAuthor Commented:
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
 
objectsCommented:
try:

outFile.println((char)('A'+i)+" " + count[i]);
0
 
objectsCommented:
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
 
chataholic4realAuthor Commented:
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
 
objectsCommented:
u need to define the max variable:
      ...
      int[] count = new int[26];
      int max = 0;
       ...
0
 
chataholic4realAuthor Commented:
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
 
objectsCommented:
> 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
 
chataholic4realAuthor Commented:
Thanx alot again..I really appreciate..it..
0
 
objectsCommented:
No worries :)
0
 
kenyapekeCommented:
Just as a by the way..how do you round off a no. e.g 1.23424 to 1.234?
0
 
chataholic4realAuthor Commented:
Just as a by the way..how do you round off a no. e.g 1.23424 to 1.234?
0
 
objectsCommented:
use DecimalFormat:

import java.text.*;


float f = 1.23424;
DecimalFormat df = new DecimalFormat("0.000");
String s = df.format(f);
0
 
CEHJCommented:
>>
..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
 
CEHJCommented:
Also you should not mix the functionality of reading the source file and writing the result - they should be kept separate
0
 
objectsCommented:
:)
0

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 9
  • 8
  • 8
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now