简体   繁体   中英

I can't figure out why this Recursion isn't working

I am learning about Recursions, and I haven't fully grasped it yet. So here I am trying to do an assignment on recursion but I'm stuck.

In this assignment, I am supposed to ask the user to input phrases, and the program determines whether it's a palindrome or not. We are supposed to accomplish this task using recursions.

This is the section with the recursion, and I can't quite figure out how to tackle it, as when I run it, I get no error, but it always comes up as false.

I'm using a ArrayList to keep all the user input.

Here's the code I've got right now

//instance variables
private boolean det;
private String input;
private String inputHelp;

//constructor
public RecursivePalindrome(String i)
{
    det = false;
    input = i;
    inputHelp = "";
}

//determines if the method is a palindrome or not using recursions
public boolean palindrome(String b)
{

    if(inputHelp.length() == 0)
    {
        det = true;
    }
    if(inputHelp.substring( 0 , 1 ).equals(inputHelp.substring( inputHelp.length() )))
    {
        inputHelp = inputHelp.substring( 1, inputHelp.length());
        palindrome(inputHelp);
    }
    else 
    {
        det = false;
    }
    return det;
}

There are three mistakes. First, note the substring documentation : second parameter is the end index "exlusive". Secondly, you need to use the result of the recursive call. And finally (as pointed out correctly by ajb in the comments), you should account for palindromes with odd letter count (first condition):

if (inputHelp.length() <= 1)
{
    det = true;
}
else if (inputHelp.substring(0, 1)
             .equals(inputHelp.substring(inputHelp.length() - 1)))
{
    inputHelp = inputHelp.substring( 1, inputHelp.length() - 1);
    det = palindrome(inputHelp);
}
else 
{
    det = false;
}

Also, you can make it a bit more readable:

public boolean palindrome(String b)
{
    if (b.length() <= 1)
    {
        return true;
    }

    if (b.substring(0, 1)
           .equals(b.substring(b.length() - 1)))
    {
        return palindrome(b.substring(1, b.length() - 1));
    }

    return false;
}

Further improvements can be made - lines still seem to long, especially the second condition (left as an exercise for the reader ;)).

As far as I can tell you are never setting inputHelp to anything other than an empty string, and the string b which is passed in to your method is not used anywhere.

So the method will never call back on to itself, and even if it did the value passed in would not be used for anything, rendering the recursion useless.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM