I have made a Java prog which will accept a word and a sentence, and then prints the number of times the word occurs in the sentence...

Here is my code:

class check_number_word
{
void check(String w, String s)
    {
        int l=s.length(),n=0,d=0;
        String s1="";
        for(int j=1;j<l;j++)
            {
                s1=s.substring(d,j);
                if(s1.equalsIgnoreCase(w))
                    {
                        d=j+2;
                        j=d+1;
                        n++;
                    }
                }
                System.out.println(n);
            }
        }

But, the program is not working? Any ideas why?

There is no match because you keep incrementing i only.
Example: if you have the word Banana and want to find all a's:
In the first iteration the string 'B' is compared to 'a' and evaluates to false, the second iteration (d has remainded unchanged thus is 0 still) is comparing 'Ba' witch 'a' and evaluates to false. And therein lies the problem.

Your solution looks a little messy, I would probably store the length of the string you want to match and then iterate through the string fetching the next characters with substring. If you only want to match exact word (like hi is not counted in hill) I think you should parse the string first, trying to fetch all complete words.

hope this helps a little!

Also, consider the fact that you can jump to the next word by reading in the next chars after each word until you find the space. You know the next word is after that space.

This question has already been answered. Start a new discussion instead.