Hi all. I'm very new to java and need help figuring out how to count the number of times a specific letter is found in a file. I'm trying to read through a file test.txt and count the number of times the letter X is found in the file. I've written the following code to do this. I able to get the count of all the characters in the file but not the count of the specific letter. Am I on the right track at all?
Yes, you're on the right track. Just not all the way along the track yet.
You have some code which reads each line from the file. So far so good. Next you need some code which examines each character in that line. That would be some kind of for-loop, most likely. You don't have that yet. (You only have the code which wants to be inside that for-loop.)
Joined: Jun 30, 2011
I tried this but it gets stuck in an infinte loop.
Well, yeah. You have code which says "Keep going while j is such and such" and then you never change the value of j. So it keeps going. Forever, because j is always such and such.
But I would have written an ordinary for-loop which iterates over the characters in the string. With ordinary for-loops you don't need to worry about infinite loops, unlike with while-loops where you have to be careful to make them terminate at the right time.
Welcome to the Ranch
As for what Paul said about for loops, if you are stuck, try the Java™ Tutorials.
You can get out of your infinite while loop by moving the bit about j++ one line earlier; it is actually not in the loop. Ignore that last bit; I was mistaken.
Campbell Ritchie wrote:You can get out of your infinite while loop by moving the bit about j++ one line earlier; it is actually not in the loop. Ignore that last bit; I was mistaken.
I might have been mistaken too, I didn't see that line. (That's another reason for writing a standard for-loop, other programmers will understand it immediately, whereas with a while-loop like that it's easy to misunderstand.) However the posted code was apparently retyped from somewhere and not cut-and-pasted (I can tell because it has errors which won't compile) so it might not be the actual code being run.
Joined: Oct 13, 2005
Paul Clapham wrote:. . . I didn't see that line. . . .
That is actually because the quoted code was incorrectly indented.