Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
142 views
in Technique[技术] by (71.8m points)

java - Getting A String Index Out Of Range Error

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...