尝试以另一种方法访问对象数组时的NullPointer

时间:2016-03-23 16:10:03

标签: java arrays

我想从我班上的另一个方法访问我的对象数组。我的代码如下。我收到NullPointerException错误。

nameArray只是读取文本文件,数据存储在其中。

public class menu {

    static Scanner askInfo = new Scanner(System.in);
    public static Student ArrObj[] = new Student[15]; //instantiates an array of student objects 

    public static void main(String args[]) throws IOException {
        for (int i = 0; i < 15; i++) {
            ArrObj[i] = new Student(); //creates an array of student objects
            System.out.println("Here is the list of all children.");
            System.out.println("Which child's information do you want to enter?");
            int InName = askInfo.nextInt();
            switch (InName) {
                case 1:
                    ArrObj[i].setName(Read.nameArray[0].substring(3));
                    break;
                case 2:
                    ArrObj[i].setName(Read.nameArray[1].substring(3));
                    break;
                case 3:
                    ArrObj[i].setName(Read.nameArray[2].substring(3));
                    break;
                case 4:
                    ArrObj[i].setName(Read.nameArray[3].substring(3));
                    break;
            }
        }
        for (int i = 0; i < 15; i++) {
            System.out.println(ArrObj[i].getName());
        }
    }

}

学生班的(重要部分):

public class Student {
    private String name;      //name of student    

    public void setName(String name) {
            this.name = name;
    }

    public String getName(){
        return name;
    }
}

Read类:

import java.io.*;
import java.util.*;

public class Read {

    static String nameArray[] = new String[100]; //to be safe, declare plenty

    public static void ReadNames() throws IOException //method to read names
    {
        Scanner read = new Scanner(new File("C:\\IA\\names.txt")); //this will read the names of students
        int counter = -1; //-1 so that when incremented, the first index is 0 
        while (read.hasNext()) {
            counter++;
            nameArray[counter] = read.nextLine();
        }
    }
}

1 个答案:

答案 0 :(得分:0)

    public static void main(String args[]) throws IOException {

     Read.ReadNames();

    for (int i = 0; i < 3; i++) {
        ArrObj[i] = new Student(); // creates an array of student objects
        System.out.println("Here is the list of all children.");
        System.out.println("Which child's information do you want to enter?");
        int InName = askInfo.nextInt();
        switch (InName) {
        case 1:
            ArrObj[i].setName(Read.nameArray[0]);
            break;
        case 2:
            ArrObj[i].setName(Read.nameArray[1]);
            break;
        case 3:
            ArrObj[i].setName(Read.nameArray[2]);
            break;
        case 4:
            ArrObj[i].setName(Read.nameArray[3]);
            break;
        }

    }

    for (int i = 0; i < 3; i++) {
        System.out.println(ArrObj[i].getName());
    }

}