-1

I need to find a string element in my array but when I check to see, it always comes up as found, even if its not the case. I am trying to call a method.

    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;
Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140

2 Answers2

1

String equality should be checked with String.equals(str) method.

Try

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;
    }
Regie Baguio
  • 241
  • 5
  • 13
0

firstly you should call if(result == true){} //you performing a assignment.

Remario
  • 3,813
  • 2
  • 18
  • 25