Java中的顺序字符串搜索

时间:2013-04-11 00:39:39

标签: java string search sequential

你好再次堆栈溢出.. ers, 我创建了这段代码来顺序搜索数组以找到一个值,在本例中是一个名称。但是,我不能让它工作,它不会找到我输入的名称,并始终返回值-1。

当我将所有类型更改为INT并对年龄数组进行搜索时,它有效,所以它可能与字符串类型有关?有人可以帮助我吗?

public static void main(String [] args){

    String[] name = {"John", "bert", "Elle", "beth"};
    String[] sex = {"Male", "Male", "female", "female"};
    int[] age = {18, 25, 22, 36};
    int found;

    Scanner keyboard = new Scanner(System.in);
    System.out.println("Enter name to search: ");

    String searchName = keyboard.next();

    found = searchNames(name, searchName);

    if(found == -1)
        System.out.println("Error, not found: " + found);
    else
        System.out.println("Found At: " + found);

}

private static int searchNames(String[] name, String searchName) {

    int i = 0, foundAt = -1;
    boolean found = false;

    while (!found && i < name.length)
    {
        if (name[i] == searchName)
        {
            found = true;
            foundAt = i;
        }
        i++;
    }
    return foundAt;
}

2 个答案:

答案 0 :(得分:1)

这将很快关闭,但使用.equals()来比较字符串。

答案 1 :(得分:0)

尝试替换代码的这部分

while (!found && i < name.length)
{
    if (name[i] == searchName)
    {
        found = true;
        foundAt = i;
    }
    i++;
}

for(int i=0; i<name.length; i++)
{
    if(name[i].equalsIgnoreCase(searchName))
    {
        found = true;
        foundAt = i;
        break;
    }
}