检查父子循环函数



我正在尝试创建一个可以识别父子循环的函数。
Imagin

对象A是对象B的父对象
对象B是对象C的父对象

创建一个可以防止父子循环的函数。该函数应该至少给出两个参数(childName, parentName),如果关系创建了循环,则返回错误。在上面的例子中,如果我们传递(A, C)应该打印或传递string:

A是c的父元素

我知道如何创建这个函数(你可以用任何语言提供答案):

private static void restrict_ParentChild_Loop(Object A, Object B) throws Exception {
if (A.parent == null)
return;
if (A.parent.equals(B)) {
throw new Exception("");
} else {
restrict_ParentChild_Loop(A.parent, B);
}
}

我的主要问题是如何在Exception中提供正确的消息。("A"是"c"的父元素)

我的主要问题是如何在Exception中提供正确的消息。

我还在想为什么这不是题目本身。

既然这个问题很可能是基于意见的…我来打一针?

你的代码:

throw new Exception("");

将像这样抛出一个Exception:

java.lang.Exception: At ...

所以如果你一开始就告诉它你想要它显示什么,那就更好了:

throw new Exception(A.parent+" is the parent of "+B.child);
//This throws:
java.lang.Exception: A is the parent of C: At ...

结果是:

private static void restrict_ParentChild_Loop(Object A, Object B) throws Exception {
if (A.parent == null)
return;
if (A.parent.equals(B)) {
throw new Exception(A.parent+" is the parent of "+B.child);
} else {
restrict_ParentChild_Loop(A.parent, B);
}
}

最新更新