Iterating through another part of the dimension in a for loop throws an IndexOutOfRangeException (C #) exception

I had a problem while repeating one dimension of a two-dimensional array in a C # console application. This is the part of the game that comes up with witty answers for every time you miss a shot, or you successfully shot. Let me start with the two-dimensional boolean I made:

public static bool[,] hasResponseBeenUsedBefore = new bool[2, 11]; 

There are two rows in the first dimension. 1 - accompany answers when the blows are successful. And 2 - accompany the answers when missed.

In the method that I created to generate the answer, I try to iterate in the second dimension.

 int usedManyTimes = 0; for (int i = 0; i < hasResponseBeenUsedBefore.GetLength(1); i++) { MessageBox.Show(i.ToString()); if (hasResponseBeenUsedBefore[2, i] == true) // 2 is the dimension for unsuccessful responses { usedManyTimes++; } } 

I tried to get the length of the second dimension without success. Throws an IndexOutOfRangeException with the following information:

HResult: -2146233080

Exception message: the index was outside the array.

Any help on this would be greatly appreciated. Thank you for your time.

+6
source share
2 answers

To get an "unsuccessful" measurement, use 1 , not 2 :

 if (hasResponseBeenUsedBefore[1, i] == true) 

Arrays use zero-based indexes. When you define an array like:

 var hasResponseBeenUsedBefore = new bool[2, 11]; 

you access your elements with hasResponseBeenUsedBefore[0][0] through hasResponseBeenUsedBefore[1][10] .

+2
source

Arrays use zero-indexing. The array in the first dimension has a size of 2, so it has only indices 0 and 1. The second dimensional array has a size of 11, so they have indices from 0 to (including) 10 available.

Try

 int usedManyTimes = 0; for (int i = 0; i < hasResponseBeenUsedBefore.GetLength(1); i++) { MessageBox.Show(i.ToString()); if (hasResponseBeenUsedBefore[1, i] == true)//notice the change from [2,i] to [1,i] here { usedManyTimes++; } } 
+2
source

All Articles