Arief Muhammad Arief Muhammad - 1 month ago 7
C# Question

Getting Error 'System.IndexOutOfRangeException'

public float[] HitungFitness()
{
float[] fitness = new float[populasi];
for (var individu = 0; individu < populasi; individu++)
{
fitness[individu] = CekConstraint(individu);
}
string[] sort = new string[populasi];
for (int i = 0; i < populasi; i++)
{
sort[i] = string.Format("\nIndividu {0} :Fitness {1}",(i + 1), fitness[i]);
}
bool swapped = true;
while (swapped)
{
swapped = false;
for (int i = 0; i < populasi-1 ; i++)
{
string[] strI = sort[i].Split('.');
float fitI = float.Parse(string.Format("0.{0}", strI[1]));

string[] strJ = sort[i + 1].Split('.');
float fitJ = float.Parse(string.Format("0.{0}", strJ[1]));

if (fitI < fitJ)
{
string sTmp = sort[i];
sort[i] = sort[i + 1];
sort[i + 1] = sTmp;
swapped = true;
}
}
}
return fitness;
}


variable populasi assign = 12

A function CekConstraint is giving a return value between '0.***' to '1'

I have a problem with:

float fitI = float.Parse(string.Format("0.{0}", strI[1]));


or

float fitJ = float.Parse(string.Format("0.{0}", strI[1]));


When the
strI
or
strJ
just giving one value of array like
strJ[1]
or
stri[1]
then I'm getting the Index was outside bounds of the array. I recognize the error but how do I fix this?

Please help me.

Answer

Error is because it is not getting value in strI[1] or strJ[1]. It may have happened because of a "." is not found in sort[i]. Hence we can see put a condition based on strI and strJ array Length.

Change your inner for loop as

for (int i = 0; i < populasi-1 ; i++)
{
    float fitI = 0.0;
    float fitJ = 0.0;
    string[] strI = sort[i].Split('.');
    if(strI.Length > 1)
        fitI = float.Parse(string.Format("0.{0}", strI[1]));


    string[] strJ = sort[i + 1].Split('.');

    if(strJ.Length > 1)
        fitJ = float.Parse(string.Format("0.{0}", strJ[1]));


    if (fitI < fitJ)
    {
        string sTmp = sort[i];
        sort[i] = sort[i + 1];
        sort[i + 1] = sTmp;
        swapped = true;
    }
}