-3
Я хотел бы получить доступ к моему массиву объектов из другого метода в моем классе. Мой код выглядит следующим образом. Я получаю ошибку NullPointerException.NullPointer при попытке доступа к массиву объектов другим способом
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());
}
}
}
(важные части) класса Student:
public class Student {
private String name; //name of student
public void setName(String name) {
this.name = name;
}
public String getName(){
return name;
}
}
Прочитанные класс:
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();
}
}
}
Какая линия вы получаете NullPointer на? Вы инициализируете весь массив до его использования? –
Что такое 'askInfo'? – khelwood
askInfo - это сканер. Я просто положил его в –