-1

I am writing a java program to use a for loop and substrings to return a palindrome, but I'm confused on what to put in the substring?

This is the code I used, and the error I received:

String str2 = "";
for(int k = 2; k < sentence.length(); k++)
{
    String str3 = "";
    str3 = str2.substring(k , sentence.length()-1);
......

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: begin 2, end 22, length 0

Does anyone know how to fix this? I believe the issue is in the substring.

Abra
  • 19,142
  • 7
  • 29
  • 41

1 Answers1

0

The variable str2 is an empty string, so when you call str2.substring(k, sentence.length()-1), it is trying to extract a substring from an index that does not exist, resulting in a StringIndexOutOfBoundsException.

Here str2 is of no use. And it looks like you are trying to extract a substring from the variable sentence using the variable k as the starting index and sentence.length()-1 as the ending index.

for(int k = 0; k < sentence.length(); k++){
  String subString = sentence.substring(k, sentence.length());
  if(isPalindrome(subString)) {
    // do something
  }
}
Kiran Kandel
  • 284
  • 1
  • 9