user3822332
user3822332

Reputation: 219

Console line throwing NullPointerException?

I'm doing an assignment that involves the use of a binary tree, but the example programme we were given isn't functioning (good to know the tiny programme was tested before being given to impressionable minds). It's throwing a NullPointerException on the line "info.name= input.readLine("Enter student ID: ");"

import java.io.*;

class BinaryTree1
{   

  public static void main(String[] args) throws IOException
  {
Console input = System.console();
String line = new String();

Student info;
info = new Student();
Student root;
root=null;
System.out.println("Input student name followed by mark 10 times;");    
for(int i = 1; i < 10; i++)
{       
    info.name= input.readLine("Enter student ID: ");
    line = input.readLine();
    info.id = Integer.parseInt(line);
    root=addNode(root, info);
}

  }


  static Student addNode(Student root, Student info)
  {
if(root == null)
{
    root= new Student();
    root.left = null;
    root.right = null;
    root.name = info.name;
    root.id = info.id;
}
else
{
    if(info.id < root.id)
        root.left = addNode(root.left, info);
    else    //(info.id > root.id)
        root.right = addNode(root.right, info);
   } 
return root;
  }

}

Upvotes: 1

Views: 248

Answers (1)

prasadmadanayake
prasadmadanayake

Reputation: 1435

Using System.console() doesn't work in IDE. It only works outside the IDE

instead use Scanner like this.

Scanner s=new Scanner(System.in);
String p=s.nextLine();

If you want to use Console anyway Read this.http://illegalargumentexception.blogspot.com/2010/09/java-systemconsole-ides-and-testing.html

Note : Inside an IDE Console gives a null

Upvotes: 1

Related Questions