为什么这段代码找不到匹配记录,而它确实存在

时间:2013-05-12 11:24:28

标签: java if-statement

当检测到“检测”关键字时,程序被设计为搜索arraylist中的匹配名称,并返回索引值以指示arraylist中的索引,然后该记录将被删除。现在在arraylist中,一条记录的名称为“Testing One”,但该程序找不到该名称。我测试了它,程序返回-1表示没有这样的记录。但是当我使用println(personList.get(0).getName())时,输出显示有一个像“Testing One”这样的空格。

输出结果为:

-1

“测试一个”

名称不存在,删除失败!

else if(words[0].equalsIgnoreCase("delete"))
{
    if(words.length<2)
    {
        System.out.println("Please enter the name of record you want to delete");
    }
    else
    {   
        String name = "";
        if(Functions.nameValidation(words[1]))
        {
            for(int i = 2; i < words.length; i++)
            {
                name = words[1] + " " + words[i];
            }
            if(Functions.nameValidation(name))
            {
               int index = Functions.searchPeopleByName(personList, name);
               System.out.println(index);
               System.out.println(personList.get(0).getName())
                if(index>=0)
                {
                    personList.remove(index);
                    FileIO.outData(personList, outputFileName);
                }
                else
                {
                       System.out.println("The name does not exist, please check again");
                }
            }
            else
            {
                System.out.println("The name is invalid, please check again!!!");
            }
        }   
        else
        {
            System.out.println("The name is invalid, please check again");
        }
    }           
}

public static boolean nameValidation(String name)
{
    for (int i = 0; i < name.length(); i++) {
        if ((!Character.isLetter(name.charAt(i))) && (name.codePointAt(i) != 32))/*space*/ {
            return false;
        }
    }
    return true;
}

public static int searchPeopleByName(ArrayList<Person> personList, String name)
{
    for(int i=0; i<personList.size();i++)
    {
        if(personList.get(i).getName().equalsIgnoreCase(name))
            return i;
    }
    return -1;
}

1 个答案:

答案 0 :(得分:3)

如果任何字符有效,则返回true。如果任何字符无效,我怀疑想要返回false。