import java.util.Scanner;
import java.lang.Integer;
public class points{
private class Vertex{
public int xcoord,ycoord;
public Vertex right,left;
}
public points(){
Scanner input = new Scanner(System.in);
int no_of_pts = Integer.parseInt(input.nextLine());
Vertex[] polygon = new Vertex[no_of_pts];
for(int i=0;i<no_of_pts;i++){
String line = input.nextLine();
String[] check = line.split(" ");
polygon[i].xcoord = Integer.parseInt(check[0]);
polygon[i].ycoord = Integer.parseInt(check[1]);
}
}
public static void main(String[] args){
new points();
}
}
This is a very simple program in which I want to input n number of points into the system with their x and y co-ordinates
Sample Input :
3
1 2
3 4
5 6
However after entering “1 2” it throws a NullPointerException . I used Java debug to find the troubling line is
polygon[i].xcoord = Integer.parseInt(check[0]);
However the check variable correctly shows ‘1’ and ‘2’ . Whats going wrong ?
EDIT :
Thanks to the answers, I realized I had to initialize each element of the array to a new object using
polygon[i] = new Vertex();
Because the Vertex reference in the array is null.