我需要在数组中找到一个字符串元素,但是当我检查以查看时,即使不是这种情况,也总是会出现。我正在尝试调用方法。
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;
应使用字符串。equal.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;
}
首先,您应该致电if(result == true){} //you performing a assignment.