Search code examples
javapalindrome

Palindrome loop is always printing True


I'm new here and new to Java. I got a task to write a loop to check a palindrome with a given structure. I'm only allowed to use a for loop and an if statement. Here is my code. The result always prints as true.

package palindrom;

/**
*
* @author Edwin
*/
public class Palindromcheck {
    static boolean is_palindrom(String str) {

         int n = str.length();
         for (int i = 0; i <= (n / 2) + 1; ++i) {
             if (str.charAt(i) != str.charAt(n - i - 1)) {
                 return false;
             }
         }
         return true;
     }

     public static void main (String [] args){
         assert(is_palindrom(""));
         assert(is_palindrom("a"));
         assert(is_palindrom("aa"));
         assert(is_palindrom("aba"));
         assert(!is_palindrom("abab"));
         assert(!is_palindrom("abb"));

         if (true)
             System.out.println("Everything good!");
     }
}

Solution

  • As far as I can tell, your code works perfectly. None of the asserts should fire because you put a not ! before all the strings that aren't palindromes.

    The "if (true)" bit around the last println is a little odd. It doesn't do anything because true is always true.