-1

I've been learning Java for about a week now and had a question about base cases in recursion in this palindrome code I'm writing. Essentially when the input is any string that has the same first and last letter, the program prints that it is a palindrome (when it's not). The third if statement is the base case that's supposed to take care of stuff like this but it doesn't seem to be working and I can't tell why.

 public static boolean isPalindrome (String inputted_string, int first_letter, int last_letter) {
    
    boolean palindrome=false;

    if (first_letter == last_letter) {
      palindrome=true;
      System.out.println(palindrome + "1");  //these are just here to help me find out which if statement is executing
      return palindrome;
    }
    else if (first_letter > last_letter) {
      palindrome=true;
      System.out.println(palindrome + "2");
      return palindrome;
    }
    else if (inputted_string.charAt(first_letter) != inputted_string.charAt(last_letter)) {
      palindrome=false;
      System.out.println(palindrome + "3");
      return palindrome;
    }
    else if (inputted_string.charAt(first_letter) == inputted_string.charAt(last_letter)) {
      palindrome=true;
      System.out.println(palindrome + "4");
      isPalindrome(inputted_string, first_letter+1, last_letter-1);
    }      
    return palindrome;
  }
  • 3
    `if (first_letter == last_letter) { palindrome = true; ... return palindrome;}` what else did you expect to happen here? You're telling the code to return a value. The code obliged. You probably meant to recursively call `isPalindrome` there? – Federico klez Culloca Jul 22 '22 at 07:43

1 Answers1

0

You need to return the result of the last isPalindrome, now you always return true.

public static boolean isPalindrome (String inputted_string, int first_letter, int last_letter) {
    
    if (first_letter >= last_letter) {
      return true; //Checked all
    } else if (inputted_string.charAt(first_letter) == inputted_string.charAt(last_letter)) {
      return isPalindrome(inputted_string, first_letter+1, last_letter-1); // Maybe palindrome, check more
    }      
    return false; // Nope, not palindrome 
  }
Roger Lindsjö
  • 11,330
  • 1
  • 42
  • 53