使用userinput在2D数组中使用foreach循环替换项目

时间:2018-06-06 18:56:49

标签: c#

我有一个包含9个字符串的2D数组:

public static string[,] theGrid = new string[,] 
{
    { "1", "2", "3" },
    { "4", "5", "6"},
    { "7", "8", "9" }
};

这是我的绘制方法,格式化时髦,看起来像TicTacToe网格:

public static void drawGrid()
    {
        Console.WriteLine("- - - - - - - - -\n| {0}  |  {1}  |  {2}  " +
"|\n| \n| {3}  |  {4}  |  {5}  |\n|\n| {6}  |  {7}  " +
"|  {8}  |\n- - - - - - - - -"
, theGrid[0, 0], theGrid[0, 1], theGrid[0, 2], theGrid[1, 0],
theGrid[1, 1], theGrid[1, 2], theGrid[2, 0], theGrid[2, 1], theGrid[2, 2]);

    }

我正在尝试使用此方法遍历每个位置:

    public static void getInput()
    {
        string input = Console.ReadLine();

        if (Player.player1)
        {
            foreach (string s in theGrid)
            {
                if (input == s)
                {
                    s = Console.WriteLine("X");

                    break;
                }

我得到了异常:“无法分配给's',因为它是'foreach itteration变量'。我基本上试图让用户在网格上输入字符串的位置。程序应该循环遍历每个字符串以查看它是否与用户输入匹配,如果是,我希望将数字替换为“X”。

2 个答案:

答案 0 :(得分:1)

要修改数组元素,您需要编写如下内容:

public static void getInput()
    {
        string input = Console.ReadLine();

        if (Player.player1)
        {
                for (var row = 0; row < theGrid.GetLength(0); row++)
                {
                    for (var column = 0; column < theGrid.GetLength(1); column++)
                    {
                        if (input == theGrid[row, column])
                        {
                            theGrid[row, column] = "X";
                            break;
                        }
                    }
                }
       ...

答案 1 :(得分:0)

我不做任何输入验证,我认为你应该这样做。我也使它变得灵活,所以你可以做更多的3 X 3网格,只要它保持一个二维的字符串数组。如果您不需要/想要,可以删除.GetLength调用并将其替换为3,因为它是3乘3网格。我还假设你只有两个玩家,一个是x和o。

public static void getInput()
    {
        string input = Console.ReadLine();
        string mark = Player.player1 ? "X" : "O";
        for (int x = 0; x < theGrid.GetLength(0); x++)
        {
            for (int y = 0; y < theGrid.GetLength(1); y++)
            {
                if (!input.Equals(theGrid[x, y])) continue;
                theGrid[x, y] = mark;
                // Assuming your done with this method, so just returning because we don't need to search the rest of the grid
                return;
            }
        }
    }