Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

After validation, program is running successfully and storing the user input into last_name variable. But when I am trying to put last_name in the student Array, it gives me a null-pointer exception.If I omit the third line inside the for loop, the program is running fine. Here, "setStudentLastName" is a void method inside the Student class that accepts a string parameter

//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);
}  
share|improve this question
1  
??What language platform - Java I think...? Also, post your Student class code especially the setStudentLastName() method. Without that we cannot say what is going on. –  hagubear yesterday
1  
have u initialized your array –  Exbury yesterday
    
you allocate the array to hold the items but not the items themselves. –  Hogan yesterday

1 Answer 1

You have to initialize the object array in order to access it

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

in your code add

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

  }  
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.