简体   繁体   中英

C# Issues with if-statement and 2 arrays

The code runs up until the if statement in the second for-loop. Ive tried changing quite a lot of stuff -- added a second array so it doesn't conflict with the if statement. Debugged it and also changed the true statements of the last if but it never really passes through the 23 row and it shows System.IndexOutOfRangeException: Index was outside the bounds of the array.

            Console.WriteLine("Number of inputs: ");
            int numInput = int.Parse(Console.ReadLine());
            int[] arrayOfNumbers = new int[numInput];
            int[] arrayOfNumbersClone = new int[numInput];
            for (int inc = 0; inc < arrayOfNumbers.Length; inc++)
            {
                Console.Write("Enter {0} element: ", inc + 1);
                arrayOfNumbers[inc] = Int32.Parse(Console.ReadLine());
                arrayOfNumbersClone[inc] = arrayOfNumbers[inc];
            }
            for (int inc = 0, dec = numInput; inc2 < dec; inc2++, dec--)
            {
                if (arrayOfNumbers[inc] == arrayOfNumbersClone[dec])
                {
                    counter++;
                }
                else
                {
                }

            }
            if(counter<=0)Console.WriteLine("The array is not symmetric");
            else Console.WriteLine("The array is symmetric");

i think it is because you used inc2 in the for loop condition but never really assigned any value to it

change your code to

for (int inc2 = 0, dec = numInput; inc2 < dec; inc2++, dec--)

The error says that you trying to get index which is not existed in array. So just add check conditions:

int counter = 0;
int lengthNumbers = arrayOfNumbers.Length;
int lengthNumbersClone = arrayOfNumbersClone.Length;            
for (int inc2 = 0, dec = numInput; maxInc < dec; inc2++, dec--)
{
    if (inc2 < lengthNumbers
        && dec < lengthNumbersClone
        && arrayOfNumbers[inc2] == arrayOfNumbersClone[dec])
        {
           counter++;
        }
        else
        {                }

}

Let's say that numInput = 5.

Then you'll create an array with 5 elements. The 5th element has the index of 4 since the index starts counting at 0.

In the second loop you declare dec = numInput; Therefore, dec is now also 5.

In your if statement you request arrayOfNumbersClone[dec]. Since dec is 5, you're asking for the element on the 5th index. This is the 6th item, which doesn't exist. Therefore you get the "System.IndexOutOfRangeException"

Changing your second for-loop to the following should fix your problems

for (int inc = 0, dec = numInput - 1; inc < dec; inc++, dec--)

(Also note that the undefined 'inc2' is changed to 'inc')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM