This is for a homework assignment. The homework is not on recursion it is on tree structures. I have nearly finished the assignment, but my recursive method for moving back up a tree breaks. The tree structure is given by the class below:
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;
}
}
I’m quite certain the reason is the return null; statement in combination with my for loop. The for loop iterates over a node that doesn’t contain any children and as a result returns null. This ends the method and passes back null to my program which gives me null pointer exceptions.
I can’t remove the return null statement or it won’t compile, even though it will 100% return using the for loop.
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?
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:
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.