I'm playing around with C# trying to get the basics down pat, but I'm stumped on this odd error. I'm trying to search through an array of names, and then return the location of any matches. At the moment I'm just printing the name, but I'm able to get the location.
For some reason though, when I type a name I want to search for and hit enter, the program crashes saying "ArraySearch.exe has stopped working". Any idea whats wrong??
Pardon the nooby questions, I'm still new to this language/paradigm :p
Thanks! :)
using System;
public class Test
{
public static void Main()
{
string[] stringArray = {"Nathan", "Bob", "Tom"};
bool [] matches = new bool[stringArray.Length];
string searchTerm = Console.ReadLine();
for(int i = 1;i<=stringArray.Length;i++){
if (searchTerm == stringArray[i - 1]){
matches[i] = true;
}
}
for(int i = 1;i<=stringArray.Length;i++){
if (matches[i]){
Console.WriteLine("We found another " + stringArray[i - 1]);
}
}
}
}
i
will reach 3, which will give Out of range exception here:
matches[i] = true;
This would be easy to spot using debugging. (Try to learn using it. Very useful)
matches
has 3 elements so the index ranges from 0 to 2.