有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

当检测到“detele”关键字时,程序设计为在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) 个答案

  1. # 1 楼答案

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