java - get wrong output of a recursive method -
public static int getindexof(char ch, string str) { if (str == null || str.equals("")) { return 0; //base case }else{ char first = str.charat(0); if (ch != first) { return -1; //returns -1 when character cannot found within string }else{ int rest = str.length() - 1; if (str.charat(rest) == ch) { return rest; } return lastindexof(ch, str.substring(0, rest)); //recursive case } } }
this method returns index of input character of input string. however, when run in interaction plane, returns wrong number. example, when enter 'a' , "peach", supposed return 2, returns -1. method should return -1 when character cannot found in string. can tell me how deal it? thank you!
well why don't step through logic , see happens.
getindexof('a', "peach")
method goes in, string isn't null or empty falls through next line of code.
char first = str.charat(0); // 'p' if (ch != first) { // 'p' equal 'a'? no. return -1 return -1;
and rest of logic never execute. can see how fix problem?
Comments
Post a Comment