首页 > 解决方案 > “CS1513 } 预期”当我已经有一个 }

问题描述

我一直在尝试编写一小段代码,并且这个 CS1513 错误一直在显示。

我一直在寻找任何杂散的分号、大括号,但我找不到任何东西。在我尝试添加 try-catch 之前,代码运行良好。我是 C# 的新手,所以如果它很明显,请告诉我,因为我什么都看不到。

private static void MakePlayerMove(ref char[,] Board, ref ShipType[] Ships, ref int count)
    {
        int Row = 0, Column = 0, hitCount = 0;
        bool missile = true;
        GetRowColumn(ref Row, ref Column, ref missile);
        if (Board[Row, Column] == 'm' || Board[Row, Column] == 'h')
        {
            Console.WriteLine("Sorry, you have already shot at the square (" + Column + "," + Row + "). Please try again.");
        }
        else if (missile == false)
        {
            if (Board[Row, Column] == '-')
            {
                Console.WriteLine("Sorry, (" + Column + "," + Row + ") is a miss.");
                Board[Row, Column] = 'm';
            }
            else
            {
                Console.WriteLine("Hit at (" + Column + "," + Row + ").");
                Board[Row, Column] = 'h';
            }
        }
        try
        { //This one is causing the problem
            else if (missile == true)
            {
                Row -= 1;
                Column -= 1;
                for (int i = 0; i < 3; i++)
                {
                    for (int j = 0; j < 3; j++)
                    {
                        if (Board[Row, Column] != '-')
                        {
                            hitCount += 1;
                        }
                        Column += 1;
                    }
                    Row += 1;
                }
            }
        }
        catch (System.IndexOutOfRangeException)
        {
            Console.WriteLine("Please enter a value that is not on the edge of the board.");
            count += 1;
            throw;
        }
        Console.WriteLine($"You have {29 - count} turns left.");
    }

标签: c#

解决方案


你需要改变

try
{ //This one is causing the problem
   else if (missile == true)
   {
   }
}
catch (System.IndexOutOfRangeException)
{
}

else if (missile == true)
{
   try
   { 
   }
   catch (System.IndexOutOfRangeException)
   {
   }
}

索引超出范围异常

您真的不必处理IndexOutOfRangeException- 使代码不会抛出它是一个更好的选择。


推荐阅读