【问题标题】:NullPointerException while working with Object array使用对象数组时出现 NullPointerException
【发布时间】:2014-11-18 12:14:18
【问题描述】:

我在这个程序中收到NullPointerException。我认为声明对象数组有一些问题。

import java.util.Scanner;

class One 
{
    public static void main(String args[]) 
    {
        Scanner key = new Scanner(System.in);
        two[] obj = new two[3];

        for (int i = 0; i < 3; i++) {
            obj[i].roll = key.nextInt();
            obj[i].name = key.nextLine();
            obj[i].grade = key.nextLine();
        }

        for (int i = 0; i < 3; i++) {
            System.out.println(obj[i].roll + " " + obj[i].name + " " + obj[i].grade);
        }
    }
}

class Two 
{
    int roll;
    String name, grade;
}

【问题讨论】:

标签: java arrays object nullpointerexception


【解决方案1】:

您忘记初始化数组中的对象。如果没有这个初始化,obj[i] 包含一个空引用。

two[] obj=new two[3];
for(int i=0;i<3;i++)
{
    obj[i] = new two();
    obj[i].roll=key.nextInt();
    obj[i].name=key.nextLine();
    obj[i].grade=key.nextLine();
}

【讨论】:

    【解决方案2】:

    数组中的对象未初始化。 致电obj[i] = new Two(); 作为第一个 for 循环中的第一个语句。 顺便说一句:“二”必须是大写的“二”

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-12-27
      • 1970-01-01
      • 2011-12-03
      • 1970-01-01
      相关资源
      最近更新 更多