简体   繁体   中英

I am trying to do linear search of array elements(string) inside a list but I have a problem

I am trying to do a linear search of array elements(string) inside a list. I get the element, but I also get a message saying that no result is found. My teacher gave me the advice to put a (bool) inside the case but I do not know how to do it.

case 2:

if (loggbokList.Count == 0)// if the list is empty

   Console.WriteLine("\tthere is no inlägg in 
                        loggbokenlist  ");
else
{

    Console.Write("\tDu kan söka på titel eller på 
          inläggs datom." +
        "\n\twrite your search word here: ");

    string search = Console.ReadLine();

    foreach (string[] item in loggbokList)

    {

        // Linär sökning algoritm.
        for (int i = 0; i < inlägg.Length; i++)
        {

            if (item[i] == search)
                    // i get the element.
                Console.WriteLine("\t your search 
                           result is 
                        : " +
                    "\n\tTitle: " + item[0] + 
                    "\n\tMessage: " +
                    item[1] + "\n\t" + item[2]);


            else if (inlägg[i] != search)
                // i also get this message even if i get the element.
                Console.WriteLine("\tNot found?! ");

        }
    }     

}
break;

I need the program to find the element and print it if the search string is found, but I do not want it to write the message (not found!) also.

You have two issues with your code:

  1. Once you find the element, you should store that fact, like in a boolean variable, that you found the element, and then you can exit the loop using break
  2. The other is that you don't yet know if you haven't found the element until you have searched through the whole list, so you should move the "else if" part outside of the loop and instead use that boolean variable. Right now, if the first element isn't what you're looking for you're going to say "not found", but it might be further into the list.

Here's one way to restructure your loop and if-statement to do this:

bool found = false;
for (int i = 0; i < inlägg.Length; i++)
{
    if (item[i] == search)
    {
        // i get the element.
        Console.WriteLine("\t your search result is: " +
            "\n\tTitle: " + item[0] +
            "\n\tMessage: " +
            item[1] + "\n\t" + item[2]);
        found = true;
        break;
    }
}

if (!found)
    Console.WriteLine("\tNot found?! ");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM