Reputation: 33
Can someone tell me what is wrong with this? I'm trying to get the program to return the number of words in the string. It is stuck in an infinite loop...
int NumberNames(String wholename)
{
String testname=wholename;
int numnames=0;
int posBlank= testname.indexOf(' ');
while(testname.length()>0)
{
testname = testname.trim();
testname=testname.substring(posBlank+1,testname.length());
numnames++;
System.out.println(testname);
}
return numnames;
}
Upvotes: 0
Views: 156
Reputation: 72850
Two issues. You're not resetting the value of posBlank within your loop, and if you pass in a string without spaces, your substring always just returns the whole string. You'll need to solve both. Try this:
int NumberNames(String wholename)
{
String testname=wholename;
int numnames=1;
int posBlank= testname.indexOf(' ');
while(posBlank > 0)
{
testname = testname.trim();
testname=testname.substring(posBlank+1,testname.length());
posBlank= testname.indexOf(' ');
numnames++;
System.out.println(testname);
}
return numnames;
}
Upvotes: 3
Reputation: 46398
why not just use String.split(\\s)
instead??
String testname=wholename;
String[] words = testname.split("\\s");
sysout(words.length);
Upvotes: 2