我的申请有什么问题?你能给我一个很好的解释吗?

时间:2015-02-25 17:22:40

标签: java

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.  "));



    }
}

我找不到代码的错误。请你给我一个解释。我试图调试这个。我找不到问题。我试图修复整体代码

2 个答案:

答案 0 :(得分:2)

如果在posBlank中找不到空格字符,则此代码不会考虑-1可以是testname的事实。如果是-1,则此行仍然执行:

testname=testname.substring(posBlank+1,testname.length());

表达式posBlank+10,因此字符串不变。这会导致无限循环。

如果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;
    }