2013-04-11 54 views
0

你好再次堆棧溢出.. ERS, 我已經創建了這一點的代碼來順序搜索一個數組來找到一個值,在這種情況下,一個名稱。然而,我不能得到它的工作,它不會找到我輸入的名稱,並始終返回-1值。在Java中的順序字符串搜索

當我將所有類型更改爲INT並在年齡數組上進行搜索時,它工作,因此它可能與字符串類型有關?有人可以幫幫我嗎?

公共靜態無效的主要(字串[] 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; 
} 
+1

更換你的代碼

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

的這一部分要機智,你需要做的'名字[I] .equals(searchName)'代替。 – iamnotmaynard 2013-04-11 00:42:36

回答

1

這是要儘快關閉,但使用.equals()比較字符串。

0

嘗試

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