I am trying to make a program to find the number of characters of the longest palindrome within a word. What the program does is find all different substrings of the given string and should check if its a palindrome and then the number of characters it has.
Right now it is correctly finding all possible substrings and works if I enter an actual palindrome such as hannah
, but if i input something like banana
, I get the following error StringIndexOutOfBoundsException
.
Here is my code:
import java.util.Scanner;
public class Palindrome {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String word;
String reverseWord;
int palindromeLength = 0;
System.out.print("Enter A Word: ");
word = sc.nextLine();
reverseWord = new StringBuffer(word).reverse().toString();
if (reverseWord.equals(word))
palindromeLength = word.length();
else {
for(int i = 0; i < word.length(); i++) {
for(int j = 1; j <= word.length() - j; j++) {
String substring = word.substring(i, i + j);
String reverseSubstring = new StringBuffer(substring).reverse().toString();
if (reverseSubstring.equals(substring)) {
if (substring.length() > palindromeLength) {
palindromeLength = substring.length();
}
}
}
}
}
System.out.println(palindromeLength);
}
}
Anyone know why this is happening and how I could fix the issue?
Thanks!
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…