0

I am trying to write a method to check if a given word is a palindrome, but as of now it does not work. I suspect the error lies within the if-statement and the fact that you don't compare objects such as strings with == but instead with equals, is that right? However Java does not allow me to write: if (firstHalf.charAt(i).equals(secondHalf.charAt(j))), so what can I do to make it work? Are there other errors in the code?

public static boolean isPalindrome(String string) {
    String firstHalf = string.substring(0, string.length() / 2);
    String secondHalf = string.substring(string.length() / 2, string.length());
    for (int i = 0; i <= firstHalf.length(); i++) {
        for (int j = secondHalf.length(); j <= 0; j--) {
            if (firstHalf.charAt(i) == secondHalf.charAt(j)) {
                return true;
            }
        }
    }
    return false;
}
Community
  • 1
  • 1
Nickewas
  • 49
  • 7
  • 1
    You can use == for individual characters, this is fine. Your loop for j decrements, so you should check j>=0 instead of j<=0 (go on while j is zero or more). – JP Moresmau May 02 '21 at 10:27
  • 1
    You also return true as soon as you find a match, which is wrong. Everything needs to match for the string to be a palindrome, not only the first and last characters – JP Moresmau May 02 '21 at 10:28

3 Answers3

2

Why not do it this way?

public static boolean isPalindrome(String string){
  StringBuilder sb = new StringBuilder(string);  
  sb.reverse();  
  return sb.toString().equals(string);
}  
mbostic
  • 903
  • 8
  • 17
  • Very nice code, quite poor performance if the strings can be long. Of course, since this is most certainly some kind of homework, performance does not matter; however, since this is most certainly some kind of homework, it is probably more instructive to use the loops. – Michael Piefel May 31 '21 at 07:38
1

Your character test was backwards. All of the comparisons have to be equal for the String to be a palindrome.

Also, splitting the String is unnecessary. You can logically split the String with two indices.

Try this code.

    public static boolean isPalindrome(String string) {
        int frontIndex = 0;
        int backIndex = string.length() - 1;
        while (frontIndex < backIndex) {
            if (string.charAt(frontIndex++) != string.charAt(backIndex--)) {
                return false;
            }
        }
        return true;
    }
Gilbert Le Blanc
  • 50,182
  • 6
  • 67
  • 111
-1

you can make each character a String like so String s1 = "" + c1; and then compare them with .equals(s1, s2)

Or you can use the Character class which is a wrapper around primitive character. That would also enable you to use c1.equals(c2)