-1

As the title says, I am getting a NullPointerException at list[i].setName(name); and I can't figure out why. A Student contains a surname and a score. data.txt is in a format of first line: amount of entries second line: name (space) score, same for third, fourth etc. New at Java and on Stack Overflow, so please let me know what other details I should give. The method in question is below:

        public static Student [] readListFromFile() {
        Scanner s = new Scanner("data.txt");
        File fileName;
        boolean weGood = false;
        while (weGood == false) {
            System.out.println("Please enter the file name:");
            fileName = new File(getInput()); //user can input their own filename

                try {
                    s = new Scanner(fileName);
                    weGood = true;
                } catch (FileNotFoundException e) {
                    System.out.println("File not found, please try again");
                }
            }
        int listlength = Integer.parseInt(s.nextLine());
        Student [] list = new Student[listlength];
        for (int i = 0; i < list.length && s.hasNext() == true; i++) {
            String name = s.next();
            Double score = Double.parseDouble(s.next());
            list[i].setName(name); 
            list[i].setScore(score);
        }
        return list;
    }
Anders
  • 8,307
  • 9
  • 56
  • 88
  • 3
    Possible duplicate of [What is a Null Pointer Exception, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how-do-i-fix-it) – Andreas Oct 03 '15 at 11:24
  • 1
    `list` is an array of `listlength` null values. Debugging would have told you that. – Andreas Oct 03 '15 at 11:25

2 Answers2

4

When you create an array like

Student [] list = new Student[listlength];

then all array elements are initially null. Therfore list[i].setName(name); throws a NullPointerException.

You need to initialize the array elements before using them, e.g.

Student [] list = new Student[listlength];
for (int i = 0; i < list.length && s.hasNext() == true; i++) {
     list[i] = new Student();
     ...
wero
  • 32,544
  • 3
  • 59
  • 84
0

Yes you need to initialize the array element before using them.

Student[] list = new Student[listLength];
for(int i=0;i<list.length && s.hasNext() == true;i++){
 if(list[i] != null){
   list[i] = new Student();
 .....
 }
 }

It is a good practice to perform Null check before using any object(say it is a collection,String .etc.)

Shreekanth
  • 45
  • 7