indexOf to find all occurrences of a word in a String
<p>I'm trying to use indexOf to find all occurrences of the characters 'the' in a sentence. For example, if the sentence were "The other day I went over there", it should return 3. </p>

<p>I am able to do this up to the point where it finds the first index, but I'm unsure of how to write the loop. I originally had a for loop that searched the entire string, but it was returning the full string character length, instead of the occurrences of my specified character. How can I write a loop that will find all of the occurrences of the word? Thank you.</p>

<pre><code>import java.util.Scanner;

public class TheFinder
{
    public static void main (String[] args)
    {
        String theString = "";
        Scanner enter = new Scanner(System.in);

        System.out.println("Please enter a sentence: ");
        theString = enter.nextLine();
        int counter2 = 0;
        theString.indexOf("the");

        if (theString.indexOf("the")!= -1)
        counter2++;



        System.out.printf("The characters 'the' were found %d times", counter2);
        System.out.println();

        System.out.println("This was programmed by -----");
</code></pre>