Kenny Lin
Kenny Lin

Reputation: 45

"Wrong number of indices inside [];expected 2" error for two-dimensional array in C#

Hi I am a beginner c# learner, I did something wrong here as I know, but can't figure out where, anybody knows?

namespace translateTelNum
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        String originalContent = "";
        originalContent = box1.Text.ToUpper();

        char[,] charGroup = new char[,]
       {
        {'A','B','C' }, 
        {'D','E','F' },              
        {'G','H','I' }, 
        {'J','K','L' }, 
        {'M','N','O' },
        {'P','R','S' }, 
        {'T','U','V' }, 
        {'W','X','Y' } 
       };

        String numbers = "";

        for (int i = 1; i <= originalContent.Length; i++)
        {
            for (int a = 1; a <= charGroup.Length; a++)
            {
                for (int b = 1; b <= charGroup[a].Length; b++)
                {
                    if (originalContent[i] == charGroup[a][b])
                    {
                        numbers += a + 2;
                    }
                }
            }
            if (i == 2 && i== 7)
            {
                numbers += "-";
            }
        }

        Console.WriteLine(numbers);
    }
}
}

Error "Wrong number of indices inside [];expected 2" for the following lines:

for (int b = 1; b <= charGroup[a].Length; b++)
    if (originalContent[i] == charGroup[a][b])

Upvotes: 1

Views: 2597

Answers (1)

krivtom
krivtom

Reputation: 24916

Instead of using

for (int a = 1; a <= charGroup.Length; a++)
{
    for (int b = 1; b <= charGroup[a].Length; b++)
    {
        if (originalContent[i] == charGroup[a][b])

You should use

for (int a = 1; a <= charGroup.GetLength(0); a++)
{
    for (int b = 1; b <= charGroup.GetLength(1); b++)
    {
        if (originalContent[i] == charGroup[a,b])

There are two things that need to be changed.

First, instead of using charGroup.Length and charGroup[a].Length you should use method GetLength(dimension) to get the length of specific dimension. So in this case in order to get the number of rows you should use GetLength(0) and to get the number of columns you should use GetLength(1). See documentation of GetLength on MSDN

Second, C# multidimensional arrays are accessed by array[index1, index2, ..., indexN] and not by array[index1][index2] ... [indexN]. See documentation on MSDN

Also keep in mind that indexes of Arrays in C# start from 0, so most likely your loop should start at 0 instead of 1:

for (int a = 0; a < charGroup.GetLength(0); a++)
{
    for (int b = 0; b < charGroup.GetLength(1); b++)
    {
        if (originalContent[i] == charGroup[a,b])

Upvotes: 5

Related Questions