在java中输入数字集 - 空指针异常

时间:2012-10-06 15:27:29

标签: java nullpointerexception

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();

2 个答案:

答案 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]为空,因为它尚未初始化