The error is like this: Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 9 at java.lang.String.charAt(String.java:658) at palindrom.Palindrom.main(Palindrom.java:30)
Asked
Active
Viewed 25 times
0
-
the first character of a string is at index 0. So, someString.charAt(9) crashes with that error if the string has 9 or fewer characters (if you want the very last character of a 9-sized string, ti's .charAt(8) - because we start the count at 0). – rzwitserloot Mar 26 '20 at 03:53
1 Answers
0
Maybe you could try to compare the index and the string length before calling charAt().
public static void main() {
String str = "hello";
int index = 9;
if (index < str.length()) {
char c = str.charAt(index);
}
}

popahqiu
- 1
- 2