Reputation: 25
I have a file that contains information like this:
The number of lines varies. The professor is using other document to test the program.
I want to extract the long name from this file and print it.
Here is what I have:
public List<String> extractName(List<String> longName)
{
Data data = new Data();
Scanner scan = new Scanner(actualFile);
longName = new List<String>();
String line = scan.nextLine();
if(line.contains("---"))
{
while(line != null)
{
String[] name = line.split(" +");
longName.add(name[2]);
}
data.setLongName(longName);
}
return longName;
}
and my main
method and one other method:
public static void main(String[] args) throws FileNotFoundException{
//process file
try{
File actualFile = new File(args[0]);
System.out.println("File was processed: true");
}
catch (ArrayIndexOutOfBoundsException e)
{
System.out.println("File was processed: false. Re-enter filename.");
return;
}
Data data = new Data();
printInfo(data); // error occurs here
}
public static void printInfo(Data d){
for(int i = 0; i < longName.size(); i++) //error occurs here
System.out.println(longName.get(i));
}
and my class, in case anyone needs it:
public class Data{
private List<String> longName;
public void Data(){}
public void setLongName(List<String> theLongName){
longName = theLongName;
}
public List<String> getLongName(){
return longName;
}
}
But when I run it, I get this error:
Exception in thread "main" java.lang.NullPointerException
at project2shm.printInfo(project2shm.java:35)
at project2shm.main(project2shm.java:18)
I am so confused. I labeled where the error occurred in the code. Can anyone help me, please?
Upvotes: 1
Views: 39
Reputation: 66989
project2shm.main()
never assigns a value to the longName
variable used by project2shm.printInfo()
. That longName
variable is apparently a static variable in the project2shm
class.
You did not provide the entire source for project2shm
, but it either does not initialize longName
, or assigns null
to it. In either case, that will cause the NPE that you saw.
Upvotes: 1