嗨,我是初学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);
}
}
}
错误&#34; []内的索引数量错误;预期2&#34;对于以下几行:
for (int b = 1; b <= charGroup[a].Length; b++)
if (originalContent[i] == charGroup[a][b])
答案 0 :(得分:4)
而不是使用
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.Length
来获取特定维度的长度,而不是使用charGroup[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])