2016-08-15 42 views
1

我想通过递归方法计算字符串中的字符数。这是我在Java递归计算字符串中的字符数

public class MainClass { 

    public int length(String str) { 
     if (str == null) { 
      return 0; 
     } else { 
      return length(str.substring(1))+1; // in eclipse it says : at MainClass.length(MainClass.java:12) 
     } 
    } 

    public static void main(String args[]) {  
     MainClass m = new MainClass(); 
     System.out.println(m.length("ali"));  
    } 
} 

这行代码不起作用:return length(str.substring(1))+1; 我怎样才能正确的代码? 感谢

+3

你期望发生,如果'str'是一个空字符串的引用? (请注意,错误消息应该显示涉及的异常,而不仅仅是“在MainClass.length”中......异常非常重要,并且我期望该消息对您有用......) –

+0

当您到达在递归中你的字符串结尾,你有一个长度为0的字符串,它不是“null”。你的检查''str == null''没有意义。 – f1sh

+0

'return String.length()'? –

回答

3

你忘了,当你String参数为空字符串的情况下,包括在你的检查:

if (str == null || str.length()==0) { 
    return 0; 
} else { 
[...] 

请注意,您得到的异常包含什么错,在这个有价值的信息这可能是StringIndexOutOfBoundsException,因为您在空的String对象上调用substring(1)

1

应该

public int length(String str) { 

if (str==null||str.isEmpty()) { 
    return 0; 
}else { 
return length(str.substring(1))+1 
}