I know there are several related threads, but a lot are more advanced than what I'm trying to do. I swear, I've looked at ALL of them, on many different forums. I'm in a 2nd year Java class in college, professor is not the best...I've read the book, Googled for a while, and still need help, PLEASE!! I'm working on a Project, and this is only one of the methods.

Need to count the occurrence of "the" (in any case) from a text file, which is defined in my main method. ((Another part of the project is to replace "The" with "A" & "the" with "a" then save to a new file. I have comments in my code referencing that, but first, I'm trying to figure out how to get the count right.))

We've recently gone over String, StringBuffer, File, and Scanner classes, and this is supposed to reflect those, I'm assuming. I know the file is being passed into the method correctly, but I'm not getting into the while loop, and I'm not sure why! :(

public static void countThe(File textDoc) throws IOException {

        Scanner scannerInput = new Scanner(textDoc);
        int count = 0;   

        while (scannerInput.hasNext()) { //is there a next item?
            String nextWord = scannerInput.next(); //reads next item

            System.out.println(nextWord);//just checking to see if I got in the loop

            if (nextWord.equals("The")){
                count++;
                //replace with "A" and save to new file
            }//end if
            if (nextWord.equals("the")) {
                count++;
                //replace with "a" and save to new file
            }//end if
        }//end while loop

        System.out.println("The file contains " + count + " occurrences of \"the\"");

    }//ends countThe method

Can anyone help me figure out why I'm not getting in my while loop? It looks right to me, based on the examples I see in the book, and what we've done in other programs, I've got to be missing something really stupid...PLEASE!! :{

1) if its not going in while loop then it means the file u are specifying is empty
2) Remove Declaration out of Loop , i mean

String s;
loop
s = "something";
loop close

For debugging To see if there is anything in the file, print out the File's length.

I tried that before I posted - I did a

System.out.println(textDoc.length());

outside of the while loop, and it printed the length correctly.

Your code works for me.

Hmmm...ok, then I just need to figure out why it's not working on my machine :( Thanks for taking the time to look at it! I appreciate it!!!

This article has been dead for over six months. Start a new discussion instead.