I used StringTokenizer
to get the tokens of a string. But I get two different outputs when I tried to print all the tokens in that StringTokenizer
, using a for-loop and a while-loop.
String string="She is an attractive girl, isn't she?";
StringTokenizer stringTokenizer=new StringTokenizer(string,",");
when I tried to print all the tokens using a for loop
for (int i=0;i<stringTokenizer.countTokens();i++)
System.out.println(stringTokenizer.nextToken());
output
She is an attractive girl
when I tried to print all the tokens using a while loop
while (stringTokenizer.hasMoreElements())
System.out.println(stringTokenizer.nextToken());
output
She is an attractive girl
isn't she?
I want to know why the while loop gives the expected two tokens and the for loop doesn't gives the two tokens.