Reputation: 81
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
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
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
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