Search code examples
javarecursionpalindrome

Checking to see if a string is a palindrome or not


I am very close to finishing my one practice problem that deals with a palindrome and a string parameter and I am stuck with the main method to call the method. Every time I compile my code it compiles, but then when I go to input data, it keeps on running and does not give me a result. Can anyone aid in me in what I need to do to get it to return the result? The problem just asks to create a method that checks if it is a palindrome, my main method to test it is what is giving me trouble.

This is my code:

import java.util.*;
public class TestisPalindrome
{
  public static boolean isPalindrome(String str) {
    int left = 0;
    int right = str.length() -1;

    while(left < right) {
      if(str.charAt(left) != str.charAt(right)) {
        return false;
      }
    }
    left ++;
    right --;

    return true;
  } 

  public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    System.out.println("Enter a string to see if it is a palindrome or not: ");
    String st1 = scan.nextLine();
    System.out.println(isPalindrome(st1));
  }
}

Solution

  • right & left increment should be in while loop

    while(left < right)
         {
            if(str.charAt(left) != str.charAt(right))
            {
                return false;
            }
            left ++;
            right --;
        }