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

标签 c# arrays multidimensional-array indexing indices

您好,我是初学者 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);
    }
}
}

以下行的错误“[] 内的索引数量错误;预期为 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)。参见 documentation of GetLength on MSDN

其次,C# 多维数组由 array[index1, index2, ..., indexN] 而不是 array[index1][index2] ... [indexN]。参见 documentation on 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])

关于c# - C#二维数组"Wrong number of indices inside [];expected 2"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31499202/

相关文章:

c# - 如何让 C# 查询组件识别从 sql 存储过程中的临时表返回的数据列

c++ - 算法:取出数组的每第 4 项

javascript - 如何在没有for循环的情况下在JavaScript中显示数组?

python - 在 numpy 数组上使用二进制结构迭代以获得单元格总和

c# - Color 结构的最优雅的 XML 序列化

c# - 如何加速 C# 的 MongoDB 反序列化

java - 在 Java 中高效格式化字符串数组

java - 如何在 Arraylist 中声明 String[]?

java - 如何避免 servlet 将多维字符串数组转换为一维字符串数组?

c# - 在 c# 中延时后自行停止录音机(使用 NAudio)