2015-11-16 123 views
0

所以我沒有錯誤,在我的代碼,但由於某種原因,如果數組包含它線性字符串數組的搜索

public static void linSrch(String[] names) { 
    Scanner inputDevice = new Scanner(System. in); 
    System.out.println("Please enter search"); 
    String search; 
    search = inputDevice.nextLine(); 
    boolean searchReturn; 
    for (int index = 0; index < names.length - 1; index++) { 
     if (names[index] == search) { 
      searchReturn = true; 
     } 
    } 
    if (searchReturn = true) { 
     System.out.println(search + " is found in the array."); 
    } else { 
     System.out.println(search + " not found in the array"); 
    } 
} 
+1

若要比較兩個字符串是否相等,請執行'names [index] .equals(search)'而不是使用'==' –

+1

另外,'if(searchReturn = true){'不檢查是'searchReturn '是'true'。它**將值'true'賦予變量'searchReturn'。你只需要'if(searchReturn){...' – azurefrog

回答

1

而是寫作:

if (names[index] == search) { 
    searchReturn = true; 
} 

你必須寫:

if (names[index].equals(search)) { 
    searchReturn = true; 
} 

因爲,在==檢查存儲器地址是相等的或不非原始數據類型的情況下。

而且也絕不能忘記:

if (searchReturn = true) { 
    System.out.println(search + " is found in the array."); 
} 

改變:

if (searchReturn) { 
    System.out.println(search + " is found in the array."); 
} 

因爲,你要分配,而不是檢查。

+1

謝謝,把我放在正確的軌道上,我結束了它的改造,並使用startsWith,endWith,幷包含我的需求,但這引導我在我需要去的方向!非常感謝。 – Kiotzu

2

下面的代碼我的搜索返回的真實結果無論

if (searchReturn = true) 

將只分配searchReturn爲真,並將執行其中的代碼。

,而不是這個代碼,您應將其更改爲

if (searchReturn) 

將運行時searchReturn是真的

也比較strrings使用equals方法,而不是==

+1

或者只是'if(searchReturn)',它就更乾淨了。 –