System.Indexoutofrangeexception: Index outside matrix boundaries

Asked

Viewed 35 times

0

Good morning! I am working on a project for my PAP, and for a company and I cannot understand what this mistake is, I have already researched in several places but still do not understand, I need to solve this mistake as soon as possible! My program is passing all the data from the Internet read by the sensor, to the console c#, sometimes the program works normally other times of error... I’ll put the code that makes me wrong:

 internal static class Program
   {
       public static void Main(string[] args)
       {
           var myPort = new SerialPort {BaudRate = 9600, PortName = "COM4"};
           myPort.Open();""

           string humidade = "", temperatura = "", heatIndex = "", lpgGas = "", monoCarbo = "", smoke = "", tempo = ""; 

           var macAddr = 
           (
               from nic in NetworkInterface.GetAllNetworkInterfaces()
               where nic.OperationalStatus == OperationalStatus.Up
               select nic.GetPhysicalAddress().ToString()
           ).FirstOrDefault();
           Console.WriteLine("Mac adress do pc: {0}", macAddr);
           
           while (true)
           {
                   var dataRx = myPort.ReadLine(); 
                  

                   var underscore = dataRx.Split('_');
                   humidade = underscore[1];
                   temperatura = underscore[2];
                   heatIndex = underscore[3];
                   tempo = underscore[4];
                   lpgGas = underscore[5];
                   monoCarbo = underscore[6];
                   smoke = underscore[7];
                   
                 
                   Console.WriteLine(tempo);
                   Console.WriteLine(humidade);
                   Console.WriteLine(temperatura);
                   Console.WriteLine(heatIndex);
                   Console.WriteLine(lpgGas);
                   Console.WriteLine(monoCarbo);
                   Console.WriteLine(smoke);
                   Console.WriteLine("___________________");
     
           }

       }
 
   }
  • 1

    error means you are reading some index that does not exist in the array, for example you are missing position 5, 6,7, etc. put this in the array try/catch to capture the error and show what you have in the variable underscore and you’ll find the problem

1 answer

1

This error says that you are trying to access a non-existent index in the array.

Example: we have an array of integers with 5 values, that is, to access the first element, we start at index 0, second element at index 1 and so on.

[1, 2, 3, 4, 5]

Considering the above array, if we try to access index 5, array[5], we will receive the error IndexOutOfRangeException, because the array only goes up to index 4.

Observing: C# arrays always start at index 0.

Back to your problem, you have an array stored in the name variable underscore where you ALWAYS expect there to be 8 elements in that array (because the last element you try to access is index 7 underscore[7]). It turns out that the way you get the values of this array is by manual data entry Console.ReadLine(), that is, it has big chances of errors because you are expecting data in a specific format abc_123_456_def (for example) and it may be that these data arrive in an incorrect format. The ideal would be to create a validation to know if the data is in the format you want, and if they are correct, you can use them.

while (true)
{
    var dataRx = myPort.ReadLine();          

    var underscore = dataRx.Split('_');

    // Validação para não quebrar a aplicação e continuar o fluxo das próximas leituras de dados
    if (underscore.Length < 8)
    {
        Console.WriteLine("Os dados recebidos não estavam no formato correto.");
        continue;
    }

    humidade = underscore[1];
    temperatura = underscore[2];
    heatIndex = underscore[3];
    tempo = underscore[4];
    lpgGas = underscore[5];
    monoCarbo = underscore[6];
    smoke = underscore[7];
                          
    Console.WriteLine(tempo);
    Console.WriteLine(humidade);
    Console.WriteLine(temperatura);
    Console.WriteLine(heatIndex);
    Console.WriteLine(lpgGas);
    Console.WriteLine(monoCarbo);
    Console.WriteLine(smoke);
    Console.WriteLine("___________________"); 
}

Another possible problem that I imagine might be, is that you started to take the data at index 1, that is, maybe you didn’t remember that the array starts at index 0. If that’s the case, just subtract 1 from each index.

while (true)
{
    var dataRx = myPort.ReadLine();          

    var underscore = dataRx.Split('_');

    // Validação para não quebrar a aplicação e continuar o fluxo das próximas leituras de dados
    if (underscore.Length < 7)
    {
        Console.WriteLine("Os dados recebidos não estavam no formato correto.");
        continue;
    }

    humidade = underscore[0];
    temperatura = underscore[1];
    heatIndex = underscore[2];
    tempo = underscore[3];
    lpgGas = underscore[4];
    monoCarbo = underscore[5];
    smoke = underscore[6];
                          
    Console.WriteLine(tempo);
    Console.WriteLine(humidade);
    Console.WriteLine(temperatura);
    Console.WriteLine(heatIndex);
    Console.WriteLine(lpgGas);
    Console.WriteLine(monoCarbo);
    Console.WriteLine(smoke);
    Console.WriteLine("___________________"); 
}

I would continue with the validation, so you avoid future problems if the data does not arrive in the format you expect.

I hope I’ve helped.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.