I would like to access my array of objects from another method in my class. My code is as follows. I get a NullPointerException error.
The nameArray
is simply reading a text file, and data is being stored in it.
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());
}
}
}
The (important parts of) Student class:
public class Student {
private String name; //name of student
public void setName(String name) {
this.name = name;
}
public String getName(){
return name;
}
}
The Read class:
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();
}
}
}