I need to create an array of trees and take a letter typed by a user and place it into a node. I am getting a NullPointerException error with forest[i].root. How can I fix this?
class TreeApp
{
public static void main(String[] args) throws IOException
{
Tree forest[] = new Tree[10];
Scanner kb = new Scanner(System.in);
for(int i = 0; i < 10; i++)
{
System.out.println("Insert a letter: ");
Node newNode = new Node();
newNode.iData = kb.next().charAt(0);
System.out.println("node: " + newNode.iData );
forest[i].root = newNode;
}
}
}
The above statement creates an array of type
Tree, but it does not store anyTreeinstances into the array. So, your array elements are initialized with defaultnullvalue.You need to initialize your array elements first before accessing them.
Add this line in your for loop: –
before accessing
forest[i].root.