C# 中二维数组的"Wrong number of indices inside [];expected 2"错误



嗨,我是c#初学者,我知道我在这里做错了什么,但不知道在哪里,有人知道吗?

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 number of indexes inside [];expected 2"

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

不使用

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

你应该使用

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

有两件事需要改变。

首先,不使用charGroup.LengthcharGroup[a].Length,而使用GetLength(dimension)方法得到特定维度的长度。所以在这种情况下,为了得到行数,你应该使用GetLength(0),为了得到列数,你应该使用GetLength(1)。参见MSDN上GetLength的文档

其次,c#多维数组是由array[index1, index2, ..., indexN]访问的,而不是由array[index1][index2] ... [indexN]访问的。参见MSDN

上的文档

还要记住,c#中数组的索引从0开始,所以很可能你的循环应该从0开始,而不是从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])

相关内容

  • 没有找到相关文章