2015-11-16 118 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)',它就更干净了。 –