次のコードは、文字列を指定して、文字列内の小文字の 'x' 文字の数を再帰的に (ループなしで) 計算しようとしています。
コードに次のエラーがあります: Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
このコードの主な方法は次のとおりです。
public static void main(String [] args)
{
System.out.println(countX("hx1x"));
}
実際のコードは次のとおりです。
public static int countX(String str)
{
if(str.charAt(0) != 'x')
{
if(str.indexOf('x') >= 1)
{
return countX(str.substring(1, str.length()));
}
else
{
return 0;
}
}
else
{
return 1 + countX(str.substring(1, str.length()));
}
}