[英]I don't understand why all the data gets printed in the arrange method correctly but does not get printed in the print method
In tree
class there is a method called arrange()
.在
tree
类中,有一个方法叫arrange()
。 When I print any node value within the arrange()
method the value comes to be accurate, but when I use the method print()
in tree
class I get a NullPointerException
.当我在
arrange()
方法中打印任何节点值时,该值变得准确,但是当我在tree
类中使用方法print()
,我得到一个NullPointerException
。 Please help!请帮忙!
public class Node {
Node lnode;
Node rnode;
int data;
public Node(String d) {
data = Integer.parseInt(d);
this.rnode = null;
this.lnode = null;
}
}
public class tree {
public void arrange(String s[], int n, Node r) {
Node root = new Node(s[0]);
for (int i = 1; i < n; i++) {
r = root;
if (Integer.parseInt(s[i]) > root.data && root.rnode == null) {
root.rnode = new Node(s[i]);
} else if (Integer.parseInt(s[i]) < root.data && root.lnode == null)
root.lnode = new Node(s[i]);
while (!(r.rnode == null) && (Integer.parseInt(s[i])) > r.data) {
r = r.rnode;
if (Integer.parseInt(s[i]) > r.data && r.rnode == null)
r.rnode = new Node(s[i]);
else if (Integer.parseInt(s[i]) < r.data && r.lnode == null)
r.lnode = new Node(s[i]);
}
while (!(r.lnode == null) && (Integer.parseInt(s[i])) < r.data) {
r = r.lnode;
if (Integer.parseInt(s[i]) > r.data && r.rnode == null)
r.rnode = new Node(s[i]);
else if (Integer.parseInt(s[i]) < r.data && r.lnode == null)
r.lnode = new Node(s[i]);
}
}
System.out.println(root.rnode.data);
}
public void print(Node r) {
System.out.println(r.rnode.data);
}
}
Main method:主要方法:
Node root;
int n;
System.out.println("Enter the number of elements you want to enter into the bst: ");
Scanner sc = new Scanner(System.in);
n = Integer.parseInt(sc.nextLine());
System.out.println("Enter the elements you want to enter into the bst: ");
Scanner s = new Scanner(System.in);
String st[] = new String[n];
st = s.nextLine().split(" ");
root = new Node(st[0]);
tree t = new tree();
t.arrange(st, n, root);
t.print(root);
The variable root
is a reference to a Node
object, which is passed by value to the arrange
method.变量
root
是对Node
对象的引用,该对象按值传递给arrange
方法。 This means that every assignment you make to r
inside arrange
(that is, every time you use the =
operator) will only last as long as you stay inside that method.这意味着每次您对分配
r
内arrange
(即每次使用时间=
运算符)将仅持续只要你保持这种方法内。
When your method returns, the value of root
will be the same as before, thus triggering your NullPointerException
when you try to access r.rnode.data
.当您的方法返回时,
root
的值将与以前相同,因此当您尝试访问r.rnode.data
时会触发您的NullPointerException
。
Now that you know the problem, I would suggest you try to find a solution on your own.既然您知道问题所在,我建议您尝试自己找到解决方案。 As the comments suggested, it is not that difficult!
正如评论所暗示的那样,这并不难!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.