Solved

creating an ouput file to store the results

Posted on 2004-04-20
26
300 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
Comment Utility
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
Comment Utility
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
Comment Utility
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
 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
So do i take it that 'watu.txt' contains lines of text composed of capital letters?
0
 

Author Comment

by:chataholic4real
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
try:

outFile.println((char)('A'+i)+" " + count[i]);
0
6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

 
LVL 92

Expert Comment

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

Author Comment

by:chataholic4real
Comment Utility
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
Comment Utility
> 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
Comment Utility
Thanx alot again..I really appreciate..it..
0
 
LVL 92

Expert Comment

by:objects
Comment Utility
No worries :)
0
 

Expert Comment

by:kenyapeke
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
>>
..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
Comment Utility
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
Comment Utility
:)
0

Featured Post

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
countAbc challenge 9 49
What is JNDI datasource in spring 1 36
Running Jira on Raspberry PI 2? 3 117
Java asynchronous logging 4 31
Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
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…
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.

771 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

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now