あなたはほとんどそこにいる、しかし、あなたはstr
の最初の文字が'x'
でない場合を修正する必要があります。 str.charAt(0) != 'x'
の場合、再帰的にcountX
をstr
にコールするので、現在行っている処理は無限再帰を引き起こします。しかし、str
は、その最初の文字として'x'
を持っていなかったものと同じ文字列がまだあるので、それは、何度も何度も何度もstr
上などをcountX
を呼び出すために起こっている...だから、唯一str.substring(1)
その最初の文字の上にcountX
を呼び出すためのソリューションですそのような'x'
ないが、
前
public int countX(String str) {
if(str.length()==0){
return 0;
}
if(str.charAt(0)=='x'){
return 1 + countX(str.substring(1));
}
else{
return countX(str.substring(1));
}
}
あなたの方法をやっていた何を
は、ここでは、コールスタックトレースは次のようになります方法です
、のは、私が"Hello"
にcountX
と呼ばれるとしましょう新しいソリューションは、溶液中で、我々は常にベースケース(str.length()==0
)に取得する方法を持っているか
call countX("Hello")
"Hello".length() != 0 so we move on to the next condition
"Hello".charAt(0) != 'x' so we call countX("ello")
call countX("ello")
"ello".length() != 0 so we move on to the next condition
"ello".charAt(0) != 'x' so we call countX("llo")
call countX("llo")
"llo".length() != 0 so we move on to the next condition
"llo".charAt(0) != 'x' so we call countX("lo");
call countX("lo")
"lo".length() != 0 so we move on to the next condition
"lo".charAt(0) != 'x' so we call countX("o");
call countX("o")
"o".length() != 0 so we move on to the next condition
"o".charAt(0) != 'x' so we call countX("");
call countX("")
"".length() == 0 so return 0
return 0
return 0
return 0
return 0
return 0
お知らせを何
call countX("Hello")
"Hello".length() != 0 so we move on to the next condition
"Hello".charAt(0) != 'x' so we call countX("Hello")
call countX("Hello")
"Hello".length() != 0 so we move on to the next condition
"Hello".charAt(0) != 'x' so we call countX("Hello")
call countX("Hello")
"Hello".length() != 0 so we move on to the next condition
"Hello".charAt(0) != 'x' so we call countX("Hello");
.
.
.
infinite recursion
。以前は、メソッドが基底ケースに達することを妨げるインスタンス(xではない文字に遭遇したとき)が存在するのに対し、
ヘイ・アレン、[尋ねる]をチェックしてください - より具体的な質問の横にいくつかのコードを表示する必要があります。 – domsson
あなたはこれまでに何を試しましたか? –
コードに問題はありますか?何がうまくいかない?何かエラーが出ますか? – BackSlash