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!
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)
.