【发布时间】:2019-10-30 08:44:16
【问题描述】:
我是一名在线课程的初学者,在本课程中,我面临着从头开始制作控制台井字游戏的挑战。我决定使用二维数组来存储游戏网格的“情节”。要循环遍历数组,以便将玩家输入与数组元素进行比较,我选择了一个嵌套的 for 循环,它似乎工作正常。它识别与玩家输入匹配的正确元素,但由于某种原因,我无法更新特定元素。我希望这是有道理的。
除了使用 foreach 循环之外,我没有尝试太多其他方法,但我不知道如何让它正确地遍历多维数组。
string[,] myArray = { { "1", "2", "3", }, { "4", "5", "6" }, { "7", "8",
"9" } };
Console.WriteLine("Player 1's go - enter a number to place your turn");
string playerInput = Console.ReadLine();
try
{
int parsedInput = Int32.Parse(playerInput);
if (parsedInput > 9)
{
Console.WriteLine("Only enter a number that is in use on the game screen");
PlayerTurn(myArray);
}
}
catch (FormatException)
{
Console.WriteLine("Please input the correct format");
PlayerTurn(myArray);
}
catch (OverflowException)
{
Console.WriteLine("Only enter a number you can see on the game screen");
PlayerTurn(myArray);
}
for (int i = 0; i < myArray.GetLength(0); i++)
{
for (int j = 0; j < myArray.GetLength(1); j++)
{
if (playerInput == myArray[i,j])
{
Console.WriteLine(myArray[i,j]); // this is to check
//that the if statement is working (which it is)
myArray[i, j] = "X"; // this isnt working correctly
break;
}
}
}
当玩家按下 1 键时,我希望 myArray[0,0] 元素从“1”变为“X”,但没有任何反应。
【问题讨论】:
-
您的迭代看起来是正确的,我同意它应该可以工作。但是,您能否补充一下您是如何将
playerInput加入该程序的,以及您是如何得出对x的分配不起作用的结论? -
您如何检查它是否无法正常工作?如果我在
myArray[i, j] = "X";之后跟踪Console.WriteLine(myArray[i,j]);,它将按预期显示X。 -
@JayV 我已经编辑了帖子以包含我的玩家输入代码
-
@obscure 我在运行时检查它。如果我输入“1” 有问题的元素仍然持有“1”而不是 X。如果这是有道理的。我刚刚尝试了您所做的并且代码正在运行并且正在存储“X”但它没有在我的网格上更新它
-
您是否有机会在您的代码中重新初始化
myArray?尝试将其设为全局变量并查看结果。
标签: c# multidimensional-array nested-loops