문제

Hi I wrote a method/array I am trying to make my code swap the second number and second to last number in the index but the only number that's is swapping was my second number and my last, if you could help a newbie I would be very thank full.

static void Main(string[] args)
{
    Console.WriteLine("\n=====================\n");
    DisplayArray(A); 
    Console.WriteLine("\nSwapping Second and Second to last Number");
    SwapSecAndSecLast(A);
    DisplayArray(A);

    Console.ReadLine();
}

static void SwapSecAndSecLast(int[] array)
{
    int temp = array[1];
    array[1] = array[array.Length - 1];
    array[array.Length - 1] = temp;
}

static void DisplayArray(int[] array)
{
    Console.WriteLine("\n=====================\n");
    for (int i = 0; i < array.Length; i++)
    {
        Console.Write("{0} ",array[i]);
    }
    Console.WriteLine("\n=====================\n");
}
도움이 되었습니까?

해결책

The second to last is

array[array.Length - 2];

not

array[array.Length - 1];

... since arrays are zero-based. However, you should check if it contains enough elements.

다른 팁

Arrays are 0 based, so array[array.Length - 1] is the last element in the array. If you want the second to last, use array[array.Length - 2]

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top