当我运行 main 方法时,以下内容不断弹出:
Exception in thread "main" java.lang.NullPointerException
我检查了我的代码,但找不到任何未初始化的变量。有人能帮帮我吗?
import java.io.FileNotFoundException;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.Scanner;
public class FileIO
{
public static ArrayList<Person> readData(String fileName)
{
ArrayList<Person> personList = new ArrayList<Person>();
int index = -1;
try
{
File file = new File(fileName);
Scanner reader = new Scanner(file);
String s;
Person p = null;
boolean addressActive = false;
while (reader.hasNext())
{
s = reader.nextLine();
Scanner line = new Scanner(s);
String cmd;
if(line.hasNext())
{
cmd = line.next();
if(cmd.equalsIgnoreCase("name"))
{
index++;
p = new Person();
p.setName(line.nextLine());
personList.add(index,p);
addressActive = false;
}
else if(cmd.equalsIgnoreCase("birthday"))
{
if(line.hasNext())
{
p.setBirthday(line.nextLine());
personList.set(index, p);
}
addressActive = false;
}
else if(cmd.equalsIgnoreCase("phone"))
{
if(line.hasNext())
{
p.setPhone(line.nextLine());
personList.set(index, p);
}
addressActive = false;
}
else if(cmd.equalsIgnoreCase("email"))
{
if(line.hasNext())
{
p.setEmail(line.nextLine());
personList.set(index, p);
}
addressActive = false;
}
else if(cmd.equalsIgnoreCase("address"))
{
p.setAddress(line.nextLine());
personList.set(index, p);
addressActive = true;
}
else if(addressActive)
{
String address = p.getAddress() + " " + s;
p.setAddress(address);
personList.set(index, p);
}
else
System.out.println("Error: no command" +s);
}
}
reader.close();
return personList;
}
catch(Exception e)
{
System.out.println("Error");
return null;
}
}
}
import java.util.ArrayList;
public class Test {
public static void main(String[] args) {
ArrayList<Person> person1 = FileIO.readData("C:/Users/phoenix/Desktopsample_phonebook1.txt");
System.out.println(person1.size());
}
}
看来我没有做任何更改,问题刚刚解决!我真的不知道为什么!!!!!我花了 3 个小时才找到问题,但就在一秒钟之内,它就被解决了,而且没有让我知道发生了什么。!总之谢谢各位大侠的热心帮助~~