This week's book giveaway is in the OO, Patterns, UML and Refactoring forum.
We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Counting one character at a time from a file Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Counting one character at a time from a file " Watch "Counting one character at a time from a file " New topic
Author

Counting one character at a time from a file

G. Graz
Ranch Hand

Joined: Oct 23, 2006
Posts: 30
I am trying to count and store the frequency each letter occurs form a .txt file . I am at the point where I can read back the file but I can not get any methods to work that would count the frequency of a letter in that file .


Simple ..no problems but here is some code that I think works in regard to counting the frequency but I am missing something to get it to function correctly ? Any ideas please let me know ! Thank you .



Again something where I think it would work but just do not see the error ?



So basically , I need to read a .txt file and print out that the character 'A' appeared x number of times .

Thank you again !
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 20077
    
  30

G. Graz wrote:

That's a bad idea. The read method returns how many characters were actually read; it can be anywhere between 0 and letters.length. If it is less than letters.length, the remainder will contain the characters that were already in the array before the call to read (in this case '\0'). You'd better use the return of br.read(letters).

As for your problem, usually when counting occurrences a Map is used:

Ulf Dittmer
Rancher

Joined: Mar 22, 2005
Posts: 42958
    
  73
The standard idiom would be a loop like this:


Just to confuse you :-) , note that counting characters gets harder if the text can contain the full range of Unicode characters.
 
I’ve looked at a lot of different solutions, and in my humble opinion Aspose is the way to go. Here’s the link: http://aspose.com
 
subject: Counting one character at a time from a file
 
It's not a secret anymore!