I am trying to write a method which returns the largest character in a string according to ASCII (a character is greater if it comes later in the ASCII table). This is what I have so far,
public char maxChar (String s) {
char[] characters = s.toCharArray();
char character = characters[0];
return maxCharHelper(characters, character, 0);
}
private static char maxCharHelper(char[] characters, char character, int index) {
if (index >= characters.length - 1) {
return character;
}
if (characters[index] > character) {
character++;
}
return maxCharHelper(characters, character, ++index);
}
I receive three issues which are:
1) when string "helloWORLD"
is used it returns 107(k) instead of 111(o)
2) when string "helloworld"
is used it returns 110(n) instead of 119(w)
lastly, 3) when string "abbxL ? 12 x5y @"
is used it returns 101(e) instead of 121(y)
Not sure why this happens, is there anything wrong with my code? Any help is appreciated.
replace character++;
with character = characters[index]
and it will work!
and replace index >= characters.length - 1
with index > characters.length - 1
, else the last character wont be checked.