What it looks like:
/* File: PalindromeTester * ---------------------------- * This program lets a user enter in a string, and will respond with confirmation that the word is * or is not a palindrome. It uses a private boolean method isPalindrom(). This method goes * halfway down each character of the word and compares to see whether that character and the * character at the mirror position on the string equal each other. If they don't, then break and * returnn false, but if they do for all letters in the first half of the string, then return true. */ import acm.program.*; public class PalindromeTester extends ConsoleProgram { public void run(){ String str = readLine("Is it a palindrome? Enter string to test here:"); if (isPalindrome(str)) { println("Yes it is!"); } else println("No it isn't."); } private boolean isPalindrome(String str) { for (int i = 0; i < str.length()/2; i++) { if (str.charAt(i) != str.charAt(str.length()-i-1)) { return false; } } return true; } }
What made it tough:
When I first wrote this, I had a bug. When checking to see if a word is a palindrome, the general approach is, for all charachters "i", to compare the "ith" character with its mirror character and see if they are equal, for all characters "i". So if your word is "kook", you'd compare the first last one to see if the characters are not the same (break if they're not), see if the two middle ones are the same, and so on.
In my buggy version, this is how I did the mirror check:
"if (str.charAt(i) != str.charAt(str.length()-i))"
This is the right version:
"if (str.charAt(i) != str.charAt(str.length()-i-1))"
Why do you have to subtract the extra 1 when you're trying inspect "i"'s mirror? In short because the "str.length" method counts starting at 1 when it returns how many characters a string contains, and meanwhile the charAt(i) method returns the "ith" character in a string, but counting as if the first letter of that string is 0. So because of this, the character at the second half of the word was actually always one after it should have been.
The funny thing is, when I wrote this and ran into the error, it didn't manifest itself via a warning in the Eclipse editor, or as red text showing up in my program's response. Instead the problem killed my program completely. I'd click to run the program, it would let me load up the interface for the user and enter in a word to test, and then instead of returning a result it would abort.
I'm sure there's a reason why my program reacted to the error in that particular way, but I'm not sure what that is. Thoughts?