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();
}
}
这是一个非常简单的程序,我想用它们的x和y坐标将n个点输入到系统中
Sample Input :
3
1 2
3 4
5 6
然而,在输入“1 2”后,它会抛出NullPointerException。我使用Java调试找到令人不安的行
polygon[i].xcoord = Integer.parseInt(check[0]);
然而,检查变量正确显示“1”和“2”。怎么回事?
编辑: 感谢答案,我意识到我必须使用
将数组的每个元素初始化为一个新对象polygon[i] = new Vertex();
答案 0 :(得分:4)
因为数组中的顶点引用为空。
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] = new Vertex(); // this is what you need.
polygon[i].xcoord = Integer.parseInt(check[0]);
polygon[i].ycoord = Integer.parseInt(check[1]);
}
}
public static void main(String[] args){
new points();
}
}
答案 1 :(得分:1)
polygon [i]为空,因为它尚未初始化