Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
140 views
Welcome To Ask or Share your Answers For Others

1 Answer

This is where the exception occurs (because endIndex is larger than the length of the string):

String substring = word.substring(i, i + j);

Use this instead:

String substring = word.substring(i, word.length());

It prints out 5 for "banana" which is expected behaviour.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...