我需要在我的数组中找到一个字符串元素,但是当我查看时,它总是会被找到,即使不是这样。我想调用一种方法。
String name = "";
boolean result = false;
if (option == 5)
{
System.out.println("Please enter a students name");
name = input.next();
linearSearch(student);
if (result = true)
{System.out.println(name+" found in element ");}
else
{System.out.println(name+" not found in element ");}
}
public static boolean linearSearch(String b[])
{
String key = null;
boolean searchReturn = false;
for(int i = 0; i < b.length; i++)
{
//if key is found - return position of key i.e. n
if( b[i] == key)
searchReturn = true;
}
return searchReturn;
答案 0 :(得分:1)
应使用String.equals(str)方法检查字符串相等性。
尝试
for(int i = 0; i < b.length; i++)
{
//if key is found - return position of key i.e. n
if( b[i].equals(name))
searchReturn = true;
}
答案 1 :(得分:0)
首先你应该致电if(result == true){} //you performing a assignment.