-1

I tried to build the node object with a arraylist element for adding child node, and initialized successfully. However when i tried to add nodes into the arraylist the exception happened. How to solve the problem?

 public class nodes{
 int value=-2;
 boolean root=false;
 nodes parent;
 ArrayList<nodes>Children;
 public nodes(int value,ArrayList Children) {
     this.value=value;
     this.Children=Children;
 }
 public void setParent(nodes parent) {
     this.parent=parent;
 }
 public void Add(nodes child) {
    this.Children.add(child);
 }
   }
    public class TreeHeight {
        
        int n;
        int parent[];
        
        nodes Nodes[];
        void read() throws IOException {
            FastScanner in = new FastScanner();
            n = in.nextInt();
            ArrayList[]Children=new ArrayList[n];
            parent = new int[n];//parent is an array that contains all elements
        
            
            Nodes=new nodes [n];
            for (int i = 0; i < n; i++) {
                //parent[i]= ;
                //index[i]=i;
                Nodes[i]=new nodes(in.nextInt(),Children[i]);
            
                
            }
            //Nodes[0].Add(Nodes[1]);
            for (int vertex = 0; vertex < n; vertex++) {
                if(Nodes[vertex].value==-1) {Nodes[vertex].root=true;
                }
for(int j=0;j<n;j++) {
    if(Nodes[j].value==vertex) {
        Nodes[j].setParent(Nodes[vertex]);
        Nodes[vertex].Add(Nodes[j]);

    }
}
                }
        }
    
  • 1
    `Children[i]` will always be null. And slightly off-topic, but your code is nigh unreadable. I'd suggest you start following standard Java naming and formatting conventions. – Robby Cornelissen Jul 16 '20 at 03:28
  • Appreciate the suggestion. Is there any solution to add nodes to Children[i] without the exception? – Random_debugger Jul 16 '20 at 05:08
  • Added Children[i]=new ArrayList(); before Nodes[i]=new nodes(in.nextInt(),Children[i]); and now the problem is solved successfully. – Random_debugger Jul 16 '20 at 05:17
  • Could you specify where the naming and formatting problems are?@Robby Cornelissen – Random_debugger Jul 16 '20 at 05:18
  • Class names should be upper CamelCase; method, field and variable names should be lower camelCase. For the rest it's mostly white-space usage and indentation issues. Getting an IDE with an auto-format feature should get rid of that. – Robby Cornelissen Jul 16 '20 at 05:31

1 Answers1

0

I don't see add values for this array?

 ArrayList[]Children=new ArrayList[n];

but have get value in this line?

 Nodes[i]=new nodes(in.nextInt(),Children[i]);
LONG DO
  • 82
  • 1
  • 5