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:
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.