Comparing two strings using recursion

I had problems with a question from my programming class II and hit a brick wall, I was wondering if anyone could help?

In the request, the user is prompted to enter a line, a program to change the input line, and then compare the opposite with the original, this must be done recursively.

So far I:

public class question1 
{
public static void main(String args[])  
{

String input = JOptionPane.showInputDialog(null, "Please enter a sentence to determine if it is a palindrome.");
String backwardsinput = Reverse(input);
System.out.println(backwardsinput);
boolean Palindrome = PalindromeCheck(backwardsinput, input);

    if (Palindrome == true)

        {
        JOptionPane.showMessageDialog(null,"That is a palindrome!");
        }

    if (Palindrome == false)

        {
        JOptionPane.showMessageDialog(null,"That is not a palindrome"); 
        }

}

public static String Reverse (String input)
{
    if (input.length() <= 1)
    return input;

    else
    {
        char x = input.charAt(input.length()-1);               
        return x+Reverse(input.substring(0,input.length()-1));
    }

}



public static boolean PalindromeCheck (String backwardsinput, String input)
{

     if(input.length() == 0 || input.length() == 1)
            return true;

        if(backwardsinput.charAt(0) == input.charAt(input.length()-1))
            return PalindromeCheck(backwardsinput.substring(1, backwardsinput.length()-1), input.substring(1, input.length()-1));

        else
        return false;

       }    
}

My problem is that she tells me that this is all a palindrome, I looked at it again and again and I can’t understand why!

+5
source share
3 answers

You do the work twice (sort of).

if(backwardsinput.charAt(0) == input.charAt(input.length()-1))
                                            ^^^^^^^^^^^^^^^^

it should be

if (backwardsinput.charAt(0) == input.charAt(0))
                                             ^

You almost got it :-)


In addition, another way of expressing

if (cond)
    return something;
else
    return false;

is an

return cond && something;

so your last lines can be written as

return backwardsinput.charAt(0) == input.charAt(0) &&
       palindromeCheck(backwardsinput.substring(1, backwardsinput.length() - 1),
                                input.substring(1, input.length() - 1));

Related Question / Answer:

+6
if(backwardsinput.charAt(0) == input.charAt(input.length()-1))

. backwardsinput.charAt(0) == input.charAt(0). .

- , ,

if(backwardsinput.charAt(0) == input.charAt(input.length()-1))

char bc = backwardinput.charAt(0);
char ic = input.charAt(input.length()-1);
System.println(bc);
System.println(ic);
if (bc == ic) {

, , .

+3

, . .

, , , ( , ) .

+2

All Articles