编写卡牌游戏洗牌函数遇语法错误:提示缺闭合大括号但已闭合
问题解决:C#方法嵌套导致的语法错误
错误根源
你遇到的报错是因为C#不允许在方法内部定义另一个方法,你把shuffle函数写在了Main方法里面,这违反了C#的语法规范。编辑器给出的"缺少闭合大括号"和"需要命名空间/文件尾"提示是语法解析失败后的误导性信息,实际问题是方法嵌套。
修正后的代码
把shuffle方法移到Main方法外部,作为Program类的静态方法(因为Main是静态方法,调用静态方法无需实例化类):
using System; using System.Collections.Generic; public class Program { // 将shuffle方法移到Main外部,定义为静态方法 public static List<string> shuffle(List<string> l) { int count = l.Count - 1; List<string> ret = new List<string>(); int ind = 0; Random rng = new Random(); string card = null; while (count > -1) { // 修正:Next方法上限是排他的,原写法会取不到最后一个元素 ind = rng.Next(0, count + 1); card = l[ind]; l.RemoveAt(ind); ret.Add(card); count--; } return ret; } public static void Main() { Console.WriteLine("Hello World"); List<List<string>> playerHands = new List<List<string>>(); //💧🔥🌀🌱 (copypaste symbols) List<string> deck = new List<string> {"1💧", "2💧", "3💧", "4💧", "5💧", "6💧", "7💧", "8💧", "9💧", "1🔥", "2🔥", "3🔥", "4🔥", "5🔥", "6🔥", "7🔥", "8🔥", "9🔥", "1🌀", "2🌀", "3🌀", "4🌀", "5🌀", "6🌀", "7🌀", "8🌀", "9🌀", "🌱1", "🌱2", "🌱3", "🌱4", "🌱5", "🌱6", "🌱7", "🌱8", "🌱9"}; List<string> sDeck = new List<string> {"R🔄", "S❌", "D🔳", "X⛈", "+✨", "A🌕", "A🌑"}; List<string> vDeck = new List<string> {"V◆", "V◇", "V◈"}; // 示例调用洗牌方法,传入副本避免修改原deck var shuffledDeck = shuffle(new List<string>(deck)); foreach(var card in shuffledDeck) { Console.WriteLine(card); } } }
额外提示
- 原代码中
rng.Next(0, count)存在逻辑问题:Random.Next(int minValue, int maxValue)的maxValue是排他的,当count为0时会抛出异常,且永远取不到最后一个元素,改成rng.Next(0, count + 1)才能正确生成0到count之间的随机索引(包含count)。 - 如果你不想修改原列表,调用时应该传入原列表的副本(比如
shuffle(new List<string>(deck))),否则原列表会被RemoveAt操作清空。
内容的提问来源于stack exchange,提问作者Razzon22
相关产品推荐
相关产品推荐

