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

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

这是一个非常简单的程序,我想在系统中输入 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();

最佳答案

因为数组中的Vertex引用为空。

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

关于java - 在java中输入数字集 - 空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12761081/

相关文章:

android - Dropbox Sync Api for Android 中的奇怪错误

java - Java 中没有 StackTrace 的 NullPointerException

java - findContainingViewHolder 返回 null

java - 空指针异常

java - 为什么我的 Android 应用程序在插入行时崩溃?

java - Apache Mina 执行器过滤器

java - 通过JPA更新实体

java - 计算出来0.00

java - SWT 文本小部件的行为与命令提示符相同

java - 如何将 bean 加载到 Spring MVC 的应用程序上下文中?