Pergunta

I have an array, with number ranging from -100 to 100. Now, I have to make a method that copies the positive ones into an other array. I made this:

static int[] ArrayCopy(int[] t)
    {
        int a = 0;
        int[] g = new int[0];
        for (int i = 0; i < t.Length; i++)
        {
            if (t[i] > 0)
            {

                g[a] = t[i];
                a++;

            }

        }
        return g;

     }

The program terminates with IndexOutOfRange, and I don't get it.

Foi útil?

Solução 2

You need 2 loops. One to count how many positives there are, and then one to copy them.

static int[] ArrayCopy(int[] t)
{
    int numPositives = 0;
    for(int i = 0 ; i < t.length ; i++)
    {
        if(t[i] > 0)numPositives++;
    }

    int[] newArray = new int[numPositives];
    int curPositive = 0;

    for(int i = 0 ; i < t.length ; i++)
    {
        if(t[i] > 0)
        {
             newArray[curPositive] = t[i];
             curPositive++;
        }
    }

    return newArray
}

Outras dicas

You are initializing your array g with a size of zero. As soon as the run starts, you try to access g at a specific index - which is not present. I assume you ment to initialize your array g the following way:

int[] g = new int[t.Length];
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top