I am trying to write a program which checks whether a word is a palindrome or not. My code compiles butthe code in the isItPalindrome method doesn't seem to be run at all. I'm hoping someone can point out where i have gone wrong. Here is my code:
class Main
{
public static void main ( String args[] )
{
System.out.print ("#Enter word");
String word = BIO.getString();
String wordLowerCase = word.toLowerCase(); // converts word to lower case (only way i could think of to ignore case)
char letters[] = wordLowerCase.toCharArray(); // converts string into an array of character
while ( !word.equals ("END")){
if (isItPalindrome(letters) == true)
{
System.out.print (""+word+"");
System.out.println (" is a palindrome");
}
else if (isItPalindrome(letters) == false)
{
System.out.print (""+word+"");
System.out.println (" is not a palindrome");
}
System.out.print ("#Enter word");
word = BIO.getString();
}
}
public static boolean isItPalindrome ( char letters[]){
boolean palindrome = true;
if (letters.length%2 == 0){
for (int index=0; index<letters.length/2-1; index++) //index will finish at letters/2
{
if (letters[index] != letters[letters.length-index-1]) //checks if index is the same as its opposite letter
{
return false;
}
else //if any pairs of letters are not in ascending order then it returns fasle and breaks out of the loop
{
palindrome = true;
}
}
}
else{
for (int index = 0; index < (letters.length-1)/2-1; index++)
{
if (letters[index] != letters[letters.length-index-1]){
return false;
}
else{
palindrome = true;
}
}
}
return palindrome;
}
}
There were some issues in the main-method, for example the char-array was never updated and the palindrome-method was far to complicated, here is the working version:
public static void main(String args[]) {
System.out.print("#Enter word: ");
String word = BIO.getString();
while (!word.equals("END")) {
char[] letters = word.toLowerCase().toCharArray();
if (isItPalindrome(letters) == true) {
System.out.println(word + " is a palindrome");
} else {
System.out.print(word + " is not a palindrome");
} // OR
// Use this one-liner instead of the if:
// System.out.println(word + isItPalindrome(letters) ?
// " is a palindrome" : " is not a palindrome");
System.out.print("#Enter word: ");
word = BIO.getString();
}
}
public static boolean isItPalindrome(char letters[]) {
for (int i = 0; i < letters.length / 2; i++) {
if (letters[i] != letters[letters.length - i - 1]) {
return false;
}
}
return true;
}
Hope this helps.