Counting the number of words beginning with a CAPITAL VOWEL using a Recursive function

UserKunal123 :

This is my code below which counts and displays the number of words beginning with a capital vowel: The function count() is a recursive function which counts the number of such words.

import java.util.*;

class Check
{
    String str; int w; 

    StringTokenizer S; 
    void InputString()
    {
        Scanner sc=new Scanner (System.in);
        System.out.println("Enter a String:");
        str=sc.nextLine();
    }

    void counter(int nWord)
    {                     
        if(nWord<=S.countTokens())
        {
            String word=S.nextToken(); 
            char first=word.charAt(0); 
            if(first=='A' || first=='E' || first=='I' || first=='O' || first=='U')
            //Checking if the word begins with a CAPITAL VOWEL.
            {
                w++; 
            }
            counter(nWord+1);
        }
    }

    void display()
    {
        S=new StringTokenizer(str);
        counter(1);
        System.out.println("Given String: "+str);
        System.out.println("Number of words beginning with capital vowels = "+w);
    }

    void main()
    {
        InputString();
        display();
    }
}

For input: "Java Is An Object Oriented Programming Language." Output: number of such words=3

But clearly, there are 4 such words in the given String. I would like to know where I made a mistake. Thanks!

Robert Kock :

Javadoc says about StringTokenizer.countTokens():

Calculates the number of times that this tokenizer's nextToken method can be called before it generates an exception. The current position is not advanced.

In other words, after each call of nextToken, countTokens will return a lower number.
This causes your counter to be called not as often as you expect.

Instead of if (nWord<=S.countTokens()), try if (S.countTokens() > 0).

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=25310&siteId=1