0

why it throws exceptions in the main when I try to use this method? I doubt that there is something wrong with the return statements

public static boolean checkPalindrome(String inputString) {
    String [] letters=inputString.split("");
    int num=inputString.length();
    int middle=num%2;
    boolean plaindrome=false;
    if(middle==0){
        for(int i=0;i<num;i++){
            if(letters[i].equals(letters[num-i])){// it tells there is something wrong on this line
                plaindrome= true;
            }else{
                return false;
            }
        }
    }else{
        for(int i=0;i<num;i++){
            if(letters[i].equals(letters[num-i])){
                plaindrome= true;
            }else{
                return false;
            }
        }
    }
    return plaindrome;
}
  • 2
    Possible duplicate of [What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?](https://stackoverflow.com/questions/5554734/what-causes-a-java-lang-arrayindexoutofboundsexception-and-how-do-i-prevent-it) – Joaquin Peraza May 31 '18 at 20:49
  • The problem is that when `i=0`, you are accessing `letters[num]` and arrays start at 0. Also, not related, but you can use `inputString.charAt(i)` instead of splitting. – Nicolas May 31 '18 at 20:52
  • Change the `letters[num-i]` to `letters[num-i-1]`, you could also use `char[] letters = inputString.toCharArray();` and then use `==` instead of `.equals` - also, why have `palindrome` the variable? If you reach the final return it must be `true`. Finally, you only need to check the first half of the characters.... once you pass that point you are "double" checking. – Elliott Frisch May 31 '18 at 20:55

1 Answers1

0

As in the documentation

Thrown to indicate that an array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of the array.

Joaquin Peraza
  • 343
  • 1
  • 15