William Giron
William Giron

Reputation: 37

check the Strings if they are palindrome

I am suppose to use Boolean to check if the string is palindrome. I'm getting an error, not sure what I am doing wrong. My program already has 3 strings previously imputed by a user. Thank you, I am also using java

 public  boolean isPalindrome(String word1, String word2, String word3){

 int word1Length = word1.length();
 int word2Length = word2.length();
 int word3Length = word3.length();

 for (int i = 0; i < word1Length / 2; i++)
{
    if (word1.charAt(i) != word1.charAt(word1Length – 1 – i))
    {
        return false;
 }
}
return isPalindrome(word1);
}

for (int i = 0; i < word2Length / 2; i++)
{
if (word2.charAt(i) != word2.charAt(word2Length – 1 – i))
    {
        return false;
    }
 }
 return isPalindrome(word2);
}
 for (int i = 0; i < word3Length / 2; i++)
{
if (word3.charAt(i) != word3.charAt(word3Length – 1 – i))
{
return false;
}
}
return isPalindrome(word3);
}

  // my output should be this
 if (isPalindrome(word1)) {
  System.out.println(word1 + " is a palindrome!");
  }
  if (isPalindrome(word2)) {
  System.out.println(word2 + " is a palindrome!");
   }
  if (isPalindrome(word3)) {
  System.out.println(word3 + " is a palindrome!");
  }

Upvotes: 1

Views: 346

Answers (1)

You could do a method for it like this:

First you build a new String and than you check if it is equal.

private static boolean test(String word) {
    String newWord = new String();      
    //first build a new String reversed from original
    for (int i = word.length() -1; i >= 0; i--) {           
        newWord += word.charAt(i);
    }       
    //check if it is equal and return
    if(word.equals(newWord))
        return true;        
    return false;       
}

//You can call it several times
test("malam"); //sure it's true
test("hello"); //sure it's false
test("bob"); //sure its true

Upvotes: 2

Related Questions