Linear search for Strings in Java

codefoodgirl_99 picture codefoodgirl_99 · Dec 14, 2014 · Viewed 10k times · Source

I'm working on a code where a user inputs ten strings which is store in an array, and a search key. The code has to run a linear search based on the search key. So far this is what I've got:

import java.io.*;
class linstring
{

    String array[] = new String[10];
    String a = new String();
    public void linsearch(String string[], String search)
    {
        string = array;
        search = a;

        int i;
        int flag = 0;
        for(i = 0; i<10; i++)
        {
            if (search.equals(string[i]))
            {
                flag = 1;
                break;
            }

        }
        if (flag ==1)
        {
            System.out.println("Word found at position " +(i+1));
        }
        else
        {
            System.out.println("Word not found.");
        }
    }

    public static void main(String args[])throws IOException
    {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        linstring obj = new linstring();
        System.out.println("Enter any 10 words.");

        String enter [] = new String[10];
        int i;
        for (i = 0; i<10; i++)
        {

            enter[i] = br.readLine();

        }
        System.out.println("Enter word to be searched.");
        String search1 = br.readLine();
        obj.linsearch(enter, search1);
    }
}

No compilation errors and no runtime errors found. However, there is a huge logical error. When I search for an element which IS PRESENT in the array, it says that the search was unsuccessful. How do I solve this?

Answer

ToasteR picture ToasteR · Dec 14, 2014

Remove these lines:

string = array;
search = a;

Edit: These two lines set the reference of string to an empty String array (array) and the reference of search to an empty String (a). This means that string and search now have the same content as array and a, which is empty.