使字符串索引超出范围错误

时间:2017-02-07 22:51:54

标签: java

我正在尝试制作一个程序来查找单词中最长回文的字符数。该程序所做的是查找给定字符串的所有不同子字符串,并检查它是否为回文,然后检查它具有的字符数。

现在它正确找到所有可能的子串并且如果我输入hannah这样的实际回文,但是如果我输入banana之类的内容,我会得到以下错误StringIndexOutOfBoundsException

这是我的代码:

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);

    }
}

任何人都知道为什么会这样,以及我如何解决这个问题?

谢谢!

2 个答案:

答案 0 :(得分:0)

这是发生异常的地方(因为endIndex大于字符串的长度):

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

请改用:

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

打印出5&#34; banana&#34;这是预期的行为。

答案 1 :(得分:0)

这是我的解决方案:

class Palindrome {
  public static void main(String[] args) {
    System.out.println(longestPalindrome("" +
      "A man once told me, " +
      "\"A man, a plan, a canal, Panama!\" " +
      "But what does that mean?"));
    System.out.println(longestPalindrome("" +
      "And then he said, " +
      "\"No 'x' in Nixon\"... " +
      "Wtf?"));
  }

  private static int longestPalindrome(final String word) {
    assert word != null;
    final String sanitized = word
      .replaceAll("\\W", "")//strip non-word chars
      .toLowerCase();
    int currentWinner = 0;
    for (int i = 0; i < sanitized.length(); i++) {
      //odd palindromes
      currentWinner = Math.max(detectPalindrome(sanitized, i, 0, 0), currentWinner);
      //even palindromes
      currentWinner = Math.max(detectPalindrome(sanitized, i, 0, -1), currentWinner);
    }
    return currentWinner;
  }

  private static int detectPalindrome(final String word,
                                      final int center,
                                      final int currentIndex,
                                      final int polarity) {
    final int left = center - currentIndex;
    final int right = center + currentIndex + 1 + polarity;
    if (left >= 0
      && right < word.length()
      && word.charAt(left) == word.charAt(right)) {
      //if you're still on the string and the streak holds, check the next char
      return (detectPalindrome(word, center, currentIndex + 1, polarity));
    } else {
      //else return the longest found so far
      return currentIndex * 2 + polarity;
    }
  }
}