javapalindrome

Palindrome Program


I'm trying to write a program which will output what Palindromes will work from entering in a string and how many there are. I keep getting a lot of errors and I'm still trying to get my head around some of the harder topics in Java!

Here's what I have already, as always, all answers are greatly appreciated!

public static boolean Palindrome(String text) {
    int index;
    int palindrome;

    System.out.println("Please enter your text ");
    text = EasyIn.getString();
    for(index = 0; index < amount.length() / 2; index++) {
        if(text.charAt(index) != text.charAt(text.length() - index - 1)) {
            return false;
        }
    }
    System.out.println("The number of valid palindrome(s) is " + amount);
    amount = EasyIn.getString();
}

Solution

  • I think the problem is in amount.length(), you should use text.length(), since you are looping over the half of text. The algorithm works fine. Here is a reduced example:

    public static boolean palindrome(String text)
    {
        for (int index = 0; index < text.length() / 2; index++) {
            if (text.charAt(index) != text.charAt(text.length() - index - 1)) {
                return false;
            }
        }
        return true;
    }
    

    Note:

    Edit: As @bobbel commented, you could improve this code by assigning text.length() to a variable and using it inside the for.