当我尝试添加人员时,我仍然遇到问题。该代码假设检测无效的姓名和生日,并且不会将此人添加到 personList 中。但是,由于在代码读取之前我无法获得生日,因此只能在循环完成时添加 person 对象。当我尝试测试添加无效的人名和/或生日时会出现问题。表明:
添加人员失败:姓名无效!!
新纪录:
名称:空"
生日:未知出生日期
已添加!
Exception in thread "main" java.lang.NullPointerException
at Instruction.readInstruction(Instruction.java:272)
at EPB.main(EPB.java:12)
else if(words[0].equalsIgnoreCase("add"))
{
Person p = new Person();
String s1 = line.substring(words[0].length()).trim();
String[] s2 = s1.split(";");
if(s2.length>=2)// s2[0] = " name Testing Three" s2[1] = " birthday 13-05-1981" and s2[2]=" address.."
{
for(int i=0; i<s2.length;i++)
{
String s3 = s2[i].trim(); // "delete the leading space" s2[0] = "name Testing Three" s2[1] = "birthday 13-05-1981"
String[] s4 = s3.split("\\s+"); //s4[0] = name; s4[1] = Testing; s4[2]=Three
if(s4.length>=2) // s2[1]=birthday 13-05-1986 only has length of 2
{
if(s4[0].equalsIgnoreCase("name"))
{
//System.out.println(s4[1]);
String name="";
if(Functions.nameValidation(s4[1]))
{
for(int j=2;j<s4.length;j++)
{
name = s4[1] + " " + s4[j];
}
if(Functions.nameValidation(name))
{
p.setName(name);
}
else
{
System.out.println("Failed to add person: Invalid name!");
break;
}
}
else
{
System.out.println("Failed to add person: Invalid name!!");
break;
}
}//end of word equals to name
//-----------------------------------------------------------------
else if(s4[0].equalsIgnoreCase("birthday") && s4.length ==2)
{
if(Functions.dateValidation(s4[1]))
{
try
{
p.setBirthdayString(s4[1]);
}
catch (ParseException e)
{
//e.printStackTrace();
}
}
else
{
System.out.println("Failed to add person: Invalid Birthday Format");
break;
}
}
//end of word equals to birthday
//-----------------------------------------------------------------
boolean notFound = false;
for(Person p1: personList)
{
if(p1.getName().equals(p.getName()))
{
if(p1.getBirthdayString().equals(p.getBirthdayString()))
{
System.out.println("Information in record" +"\n" + "name: "+ p.getName() + "\n" + "Birthday: " + p.getBirthdayString() + "\n" +"has been updated");
p1.setEmail(p.getEmail());
p1.setPhone(p.getPhone());
p1.setAddress(p.getAddress());
notFound = true;
}
}
}
if (!notFound)
{
if(Functions.nameValidation(p.getName()) && Functions.dateValidation(p.getBirthdayString()))
{
System.out.println("New record: " +"\n"+"Name: " + p.getName() + "\""+ "\n"+ "Birthday: " + p.getBirthdayString() + "\nhas been added!");
personList.add(p);
}
FileIO.outData(personList, outputFileName);
}
System.out.println();
}