1

这是一个家庭作业。作业不是递归的,而是树结构的。我几乎完成了任务,但是我向后移动一棵树的递归方法中断了。树结构由以下类给出:

package lab12;

import java.io.Serializable;

public class Dog implements Serializable{

    public Dog[] children;
    public String name;

    public Dog(String name)
    {
        this.name = name;
    }

    @Override
    public String toString()
    {
        return name;
    }

} 

我很确定原因是返回 null;结合我的 for 循环的语句。for 循环遍历不包含任何子节点的节点,结果返回 null。这结束了该方法并将 null 传回给我的程序,这给了我空指针异常。

我无法删除 return null 语句,否则它不会编译,即使它会使用 for 循环 100% 返回。

public Dog findParent(Dog root, String name)
{
    String top = "Spot";
    if(top.equals(name))
    {
        System.out.println("No further records");
        System.out.println("Goodbye.");
        System.exit(0);
    }
    for(int i = 0; root.children != null && i < root.children.length; i++)
    {
        if(root.children[i].name.equals(name))
        {
            return root;
        }
        else
        {
            return findParent(root.children[i], name);
        }
    }
    return null; //Compiler still requires a return here.
}

I feel like this has to be a common problem with using for loops in non-void recursive methods. Is there a way to make the compiler happy and yet not have the extra return null statement?

4

2 回答 2

4

Your code must not work. Because both if and else clauses will return. That causes the loop only do index 0. You should change your code like the following:

public Dog findParent(Dog root, String name)
{
    String top = "Spot";
    if(top.equals(name))
    {
        System.out.println("No further records");
        System.out.println("Goodbye.");
        System.exit(0);
    }
    for(int i = 0; root.children != null && i < root.children.length; i++)
    {
        if(root.children[i].name.equals(name))
        {
            return root;
        }
        else
        {
            Dog parent = findParent(root.children[i], name);
            if (parent != null) 
                 return parent;
        }
    }
    return null;
}

Now, you can see that the last "return null" is necessary.

In most of case, compiler is smart. If it gives your warnings, you should consider what's error with your code instead just cheat compiler to avoid warning.

于 2012-12-09T09:49:19.343 回答
2

Without understanding this problem entirely, I see no reason for the "return null" statement to never execute. Perhaps you else statement should be:

return findParent(root.children[i], name);

This return will ensure that once the "parent" is found its value will be returned.

于 2012-12-09T09:46:26.397 回答