get wrong output of a recursive method

tenmienb

New Member
\[code\] 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 the character cannot be found within the string }else{ int rest = str.length() - 1; if (str.charAt(rest) == ch) { return rest; } return lastIndexOf(ch, str.substring(0, rest)); //recursive case } }}\[/code\]This my method which returns the index of the input character of the input string. However, when I run it in the interaction plane, it returns wrong number. For example, when I enter 'a' and "peach", it is supposed to return 2, but it returns -1. This method should return -1 only when the character cannot be found in the string. Can anyone tell me how to deal with it?Thank you!
 
Top