public class PersonName {
int NumberNames(String wholename)
{ // store the name passed in to the method
String testname=wholename;
// initialize number of names found
int numnames=0;
// on each iteration remove one name
while (testname.length()>0)
{ // take the "white space" from the beginning and end
testname = testname.trim();
// determine the position of the first blank
// .. end of the first word
int posBlank= testname.indexOf(' ');
// cut off word
testname=testname.substring(posBlank+1,testname.length());
// System.out.println(numnames);
// System.out.println(testname);
numnames++;
}
return numnames;
}
public static void main(String args[])
{
PersonName One= new PersonName();
System.out.println(One.NumberNames("Bobby"));
System.out.println(One.NumberNames("Bobby Smith"));
System.out.println(One.NumberNames("Bobby L. Smith"));
System.out.println(One.NumberNames(" Bobby Paul Smith Jr. "));
}
}
我找不到代码的错误。请你给我一个解释。我试图调试这个。我找不到问题。我试图修复整体代码
答案 0 :(得分:2)
如果在posBlank
中找不到空格字符,则此代码不会考虑-1
可以是testname
的事实。如果是-1
,则此行仍然执行:
testname=testname.substring(posBlank+1,testname.length());
表达式posBlank+1
是0
,因此字符串不变。这会导致无限循环。
如果posBlank
为-1
,则计算最后一个字并突破while
循环。
答案 1 :(得分:1)
问题是如果找不到空格,它将返回-1
int posBlank= testname.indexOf(' ');
posBlank将变为-1,导致posBlank + 1 = 0
并且它将导致while循环变为无限循环
你可以这样试试:
int NumberNames(String wholename)
{
wholename = wholename.trim();
String[] names = wholename.split(" ");
int numNames = 0;
for(String name : names){
if(!name.equals("")){
numNames++;
}
}
return numNames;
}