为什么for循环在2D数组中只迭代一次



我是编码新手,想知道为什么for循环只在userInput为";1〃;。当CCD_ 2为"0"时;3〃;,例如,for循环不继续迭代,只是退出for循环。

string[,] array =
{
{"1", "2", "3"},
{"4", "5", "6"},
{"7", "8", "9"}
};
Console.Write("Enter a number from 1-9");
string userInput = Console.ReadLine();
//checks if userInput is a number in the array
for (int i = 0, j = 0; i < array.GetLength(0); i++, j++)
{
if (array[i, j] == userInput)
{
array[i, j] = "X";
Console.WriteLine("Index {0} has been changed to X", array[i, j]);
break;
}
}

你正对角穿过它(i++和j++同时通过,所以你会得到0/0,1/1,2,2,…n/n(。

试试这样的东西:

string[,] array =
{
{"1", "2", "3"},
{"4", "5", "6"},
{"7", "8", "9"}
};
Console.WriteLine("X / Y");
for (int ix = 0; ix < array.GetLength(0); ix++)
{
for (int iy = 0; iy < array.GetLength(0); iy++)
{
Console.WriteLine(ix + " / " + iy);
}
}
System.Threading.Thread.Sleep(5000);

最新更新