Я делаю программу на Java, которая читает в некоторых материалах из файла и сохраняет все в массиве. Каждый слот в массиве является связанным списком. Я получаю исключение Null Pointer Exception, и я не знаю почему. Я довольно новичок в программировании, и у меня ужасное чувство, что это что-то очевидное, чего я не вижу, но это займет всех, кто смотрит на него, о, я не знаю, может быть, две секунды, чтобы понять это. .. тогда я буду чувствовать себя глупо, но в любом случае, здесь идет ...null Указатель исключения для struct в Java-программе
NPE, согласно моему отладчику (я использую Eclipse), находится в классе GiveJob. Я заметил линию со всеми шапками, чтобы облегчить ее поиск.
Моя первая мысль о NPE заключается в том, что она должна иметь какое-то отношение к тому факту, что у меня есть массив структур. Насколько я понимаю, каждый слот в массиве объектов автоматически инициализируется значением null при использовании Java, и я думал, что это будет включать в себя массив структур. Я ошибаюсь?
Любая помощь очень высоко оценили, как я был ломать голову над этим в течение некоторого времени теперь :-P
Вот класс для массива:
public class Person{
String name;
Jobs jobs;
}
Вот класс для связанный список:
public class Jobs{
String typeOfJob;
Jobs next;
}
Вот класс для придания человеку работу:
public void GiveJob(String personName, String newJob int N, Person[] people){
//go through the array of people to see if the person already exists
for(int i=0; i<N; i++){
//check to see if the person has already been added
if(people[i].jobs != null){ //NULL POINTER EXCEPTION
if(people[i].jobs.compareToIgnoreCase(newJob) == 0){
//if the person has been added, check to see if the job has
//already been added
Jobs currentNode = people[i].jobs;
while(currentNode.next != null){
//if the job has already been added, break
if(currentNode.typeOfJob.compareToIgnoreCase(newJob) == 0){
break;
}
currentNode = currentNode.next;
}
//if the job has already been added, break
if(currentNode.typeOfJob.compareToIgnoreCase(newJob) == 0){
break;
}
else{
Jobs tempNode = new Jobs();
tempNode.typeOfJob = newJob;
tempNode.next = null;
people[i].jobs.next = tempNode;
}
}//end if the job has already been added
}
//if the person has not been added yet, add him/her
else if(people[i] == null){
people[i].name = personName;
Jobs tempNode = new Jobs();
tempNode.typeOfJob = newJob;
tempNode.next = null;
people[i].jobs = tempNode;
break;
}
}//end for(int i=0; i<N; i++) - checking if the city has been added already
}//end addToAdjList method
}//end AdjacencyList class
Вот класс, содержащий основные:
import java.io.*;
import java.util.*;
public class LookingForAJob {
public static void main(String[] args) {
//read in file
try{
File filename = new File("jobListing.txt");
Scanner fin = new Scanner(filename);
//read in the number of people (N) from file
int N = fin.nextInt();
//read in the number of jobs available (M) from file
int M = fin.nextInt();
//create a new instance of GiveJob
GiveJob jobSearch = new GiveJob();
//Create the array to put the people into
Person people[] = new Person[N];
//read in information from file
for(int i=0; i<M; i++){
//get person's name
String personName = fin.next();
//get job name
String jobName = fin.next();
//put what was read in from the file into an linked list
jobSearch.GiveJob(personName, jobName, N, people);
}//end for(int i=0; i<M; i++)
}//end try
catch(FileNotFoundException e){
System.err.println("Input file not found for reading!");
System.exit(0);
}
catch(Exception e){
System.err.println("Input file not in correct format");
System.exit(0);
}
}
}
Просто хочу убедиться - вы создали экземпляры любых значений, которые вы используете в первых двух классах? – Amndeep7
Другой вопрос, связанный как с моими, так и с @Radu, сможет ли вы распечатать значение 'i', когда вы получите NPE? – Amndeep7
В некотором смысле @Radu прав, делая «Person people [] = new Person [N];' создает только массив, но не создает объекты типа Person. Вам нужно инициализировать каждый элемент массива. http://www.cs.usfca.edu/~wolber/courses/110/lectures/ArrayOfObjs.htm – madth3