【发布时间】:2015-03-10 04:48:38
【问题描述】:
给定以下代码:
private static class Node<T>
{
public Node<T> left;
public Node<T> right;
public T data;
public Node(T data)
{
this.data = data;
}
}
public static void chart()
{
//creating new node objects
Node<Integer> BOB = new Node<Integer>(16);
Node<Integer> Cat = new Node<Integer>(17);
Node<Integer> Charlie = new Node<Integer>(1);
find(Charlie,BOB,Cat);
}
如何在 IF 语句中使用对象?例如我想看看 n 或 n.data(等于 16 时的整数)是否等于对象 BOB(整数为 16),如下所示:
public static void find(Node<?> n,Node<?> f,Node<?> g)
{
//I also tried if (n == f) and all other combinations
if (n.data == f.data)//here is the problem
{
System.out.println("Found" + f);
}
if (n != null)
{
find(n.getLeft(), g, g);
System.out.print(n.data + " ");
find(n.getRight(), g, g);
}
}
结果应该是当n等于16时它会等于对象BOB(因为它是16)然后执行IF语句。笔记。我正在使用 Organisation_chart_Traversal。
【问题讨论】:
-
你参数
n、f和g是什么意思?你不应该将f传递给find的后续调用吗? -
参数 n、f 和 g 是我输入到将用作整数的方法中的三个对象。所以查理 = 1,鲍勃 = 16,猫 = 1。
-
是的,但这是什么意思?它们的描述性不是很强,因此很难确定它们扮演的角色......
-
你为什么用
Node<?>? -
这个问题毫无意义。您的评论说您有三个输入,其中两个具有相同的数据,但是您的程序有三个对象,它们都具有不同的数据。您在“这就是问题所在”的行上有一条评论,但无论您如何切片,您似乎都在比较两个不同的整数,因此没有迹象表明问题出在哪里。您引用了您未定义的
getLeft和getRight方法,并且您不知道如何设置left和right字段。
标签: java object if-statement integer traversal