0

How can I solve Exception in thread “main” java.lang.NullPointerException error [duplicate]

My code is: https://code.sololearn.com/#java The error message happens in line: for(TreeNode<String> node: this.children ) This method is to get the leafNode of a tree. Can someone help me to fix my error? thanks!

9th Oct 2018, 4:35 AM
Tuyen Pham
Tuyen Pham - avatar
10 Antworten
+ 1
so how can i fix this?
9th Oct 2018, 6:25 AM
Tuyen Pham
Tuyen Pham - avatar
0
The link is to all the Java codes in SoloLearn. NullPointerException means that you have a null variable which is used as if its not null, which means that this.children is null.
9th Oct 2018, 6:11 AM
Eldar Bakerman
0
add an if statement to check if children is null
9th Oct 2018, 6:27 AM
Eldar Bakerman
0
it will be inside the for loop?
9th Oct 2018, 6:28 AM
Tuyen Pham
Tuyen Pham - avatar
0
Yes
9th Oct 2018, 6:28 AM
Eldar Bakerman
0
I did like below but it does not work for(TreeNode<String> node: this.children ){ if(node.children.isEmpty()){ nodes.add(node); } else { nodes.addAll(getLeafNodes()); }
9th Oct 2018, 1:52 PM
Tuyen Pham
Tuyen Pham - avatar
0
do == null
9th Oct 2018, 2:10 PM
Eldar Bakerman
0
if(node.children() == null ) ??
9th Oct 2018, 2:16 PM
Tuyen Pham
Tuyen Pham - avatar
0
i fixed it. Thanks!
9th Oct 2018, 10:06 PM
Tuyen Pham
Tuyen Pham - avatar
0
Mark my answer as best if it helped to solve your problem :-)
10th Oct 2018, 3:25 AM
Eldar Bakerman