Ryan Hardin
Ryan Hardin

Reputation: 81

Palindrome Program is running but is giving an error message

This program is suppose to tell whether or not a word is a palindrome (same word forward and backward). I'm having trouble figuring out why my computer will run this program while also having an error message to go with it. Can someone please explain?

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out
of range:

code

public class Palindrome {
    public static void main(String[] args)
    {
        System.out.println("Enter word here: ");
        String a = StdIn.readLine();

        for(int i = a.length() - 1 ; i >= 0; ++i)
        {
            if (a.charAt(i) != a.charAt(a.length() - i)) System.out.println("Not a Palindrome");
            else System.out.println("Palindrome");
        }

    }
}

Upvotes: 0

Views: 78

Answers (5)

ka4eli
ka4eli

Reputation: 5424

Your program stops when exception is thrown. You have several mistakes so I decided to rewrite your code. Call this method from main:

  static void isPalindrome(String s) {
        boolean res = true;
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) != s.charAt(s.length() - 1 - i)) {
                res = false;
                break;
            }
        }
        System.out.println(res ? "Palindrome" : "Not s Palindrome");
    }

Upvotes: 0

user1886323
user1886323

Reputation: 1199

You loop iteration variable i is being incremented in the wrong direction. You should have

for(int i = 0; i < a.length(); ++i)

OR

for(int i = a.length() - 1 ; i >= 0; --i)

You also need to change

a.charAt(a.length() - i))

to

a.charAt((a.length() - 1) - i)

because charAt uses a zero based index, like all other string manipulation methods.

Upvotes: 1

Rens van der Heijden
Rens van der Heijden

Reputation: 858

You're incrementing the counter i, but you should be decrementing it, because you start at i = a.length() - 1. This is also what the exception is trying to tell you. Furthermore, you're comparing all the characters of the string twice!

Upvotes: 0

schtever
schtever

Reputation: 3250

Your for loop should be decrementing i not increasing it.

Upvotes: 0

John
John

Reputation: 61

Decrement variable i instead of incrementing it in the for loop ?

Upvotes: 0

Related Questions