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

这是一个非常简单的程序,我想在系统中输入 n 个点及其 x 和 y 坐标

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

2 回答 2

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();    
    }    
}
于 2012-10-06T15:29:12.207 回答
1

多边形[i] 为空,因为它尚未初始化

于 2012-10-06T15:33:28.077 回答