0

New to JAVA. I am getting a Null Pointer Exception at line 30 in the following. I know that an array must be initialised when it is declared to avoid getting the exception. But in this case, I do not know the size of the array to be initialised. So, can someone please explain how i can rectify this error? Can you also explain about what happens when we declare and initialise a variable? import java.util.*;

class Person {
    protected String firstName;
    protected String lastName;
    protected int idNumber;

// Constructor
Person(String firstName, String lastName, int identification){
    this.firstName = firstName;
    this.lastName = lastName;
    this.idNumber = identification;
}

// Print person data
public void printPerson(){
     System.out.println(
            "Name: " + lastName + ", " + firstName 
        +   "\nID: " + idNumber); 
   }

}

class Student extends Person{
private int[] testScores;  //exception Here

Student(String firstName,String lastName,int id,int[] scores){
         super(firstName,lastName,id);
         for(int i=0;i<scores.length;i++)
             {
                 testScores[i]=scores[i];
         }
}

char calculate(){
   int avg=0,i=0;
   for(i=0;i<testScores.length;i++)
             {
             avg=avg+testScores[i];
         }
   avg=avg/(i+1);
   if(avg>=90 && avg<=100)
       return 'O';
   else if(avg>=80 && avg<90)
       return 'E';
   else if(avg>=70 && avg<80)
       return 'O';
   else if(avg>=55 && avg<70)
       return 'P';
   else if(avg>=40 && avg<55)
       return 'D';
   else
       return 'T';
}
 }
VisnuGanth
  • 31
  • 7

1 Answers1

0

You are initializing the array wrong. That is why it's throwing the exception. There are so many ways to initialize an array.

int[]   numbers1 = new int[3];                 // Array for 3 int values, default value is 0
int[]   numbers2 = { 1, 2, 3 };                // Array literal of 3 int values
int[]   numbers3 = new int[] { 1, 2, 3 };      // Array of 3 int values initialized
int[][] numbers4 = { { 1, 2 }, { 3, 4, 5 } };  // Jagged array literal
int[][] numbers5 = new int[5][];               // Jagged array, one dimension 5 long
int[][] numbers6 = new int[5][4];              // Multidimensional array: 5x4

For more info read the Oracle tutorial for Arrays.

Anatoly Shamov
  • 2,364
  • 1
  • 13
  • 22
Durgpal Singh
  • 8,392
  • 4
  • 32
  • 45