【问题标题】:Null pointer exception while useing Userdefined array使用用户定义数组时出现空指针异常
【发布时间】:2014-11-10 20:50:16
【问题描述】:

验证后,程序成功运行并将用户输入存储到 last_name 变量中。 但是当我试图将 last_name 放入学生数组时,它给了我一个空指针异常。如果我省略了 for 循环中的第三行,程序运行良好。 这里,“setStudentLastName”是 Student 类中的一个 void 方法,它接受一个字符串参数

//Create a array using the data from user

Student student[] = new Student[numOfStudents];

for(int i=0;i<student.length;i++)
{
  int j = i+1;
  last_name = Validator.validUpperCase(sc,"Enter student "+j+" last Name: ");
  student[i].setStudentLastName(last_name);
}  

【问题讨论】:

  • ??我认为什么语言平台-Java...?此外,发布您的 Student 类代码,尤其是 setStudentLastName() 方法。没有它,我们无法说出发生了什么。
  • 你已经初始化了你的数组
  • 你分配数组来保存项目而不是项目本身。

标签: java arrays nullpointerexception


【解决方案1】:

您必须initialize 对象数组才能访问它

for(int i=0;i<length;i++)
{
    student[i]=new student();
}

在你的代码中添加

for(int i=0;i<student.length;i++)
  {
       int j = i+1;
       last_name = Validator.validUpperCase(sc,"Enter student "+j+" last Name: ");
       student[i]=new student();
       student[i].setStudentLastName(last_name);

  }  

【讨论】:

    猜你喜欢
    • 2020-03-21
    • 2014-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多