You need to enable JavaScript to run this app. C#老虎机游戏开发:无法从字符串列表随机抽取单词的排查求助
优惠活动
大模型
产品
解决方案
定价
更多

C#老虎机游戏开发:无法从字符串列表随机抽取单词的排查求助

老虎机随机单词生成功能 Bug 定位与修复

核心报错点

  • 未定义变量调用:已声明的随机数生成实例名为rand,代码中误写为不存在的random调用Next方法,直接触发编译错误。
  • 类型不匹配:原代码意图创建存储3个槽位单词的字符串列表,却错误将rand.Next()返回的整数赋值给randomList,后续执行randomList.Add(word)时会因int类型无Add方法报错。

修复方案

删除错误的var randomList = random.Next(list.Count);行,替换为正确的列表初始化代码:
var randomList = new List<string>();
其余随机取词逻辑(循环内复用已初始化的rand取列表索引)本身无问题,可保留。

修正后的SlotMachine方法代码

static void SlotMachine()
{
    Random rand = new Random();
    var list = new List<string> { "Elephant", "Computer", "Football", "Resume", "Capstone", "Crimson" };
    // 初始化存储3个槽位展示单词的列表
    var randomList = new List<string>();

    Console.Write("Enter amount of gil you want to risk: ");
    double gil = Convert.ToDouble(Console.ReadLine());
    double winningAmount = 0;

    for (int i = 1; i <= 3; i++)
    {
        string word = list[rand.Next(list.Count)];
        randomList.Add(word);
        Console.Write(word + " ");
    }
    Console.WriteLine();

    if (randomList[0] == randomList[1] && randomList[1] == randomList[2])
    {
        winningAmount = gil * 3;
    }
    else if (randomList[0] == randomList[1] || randomList[0] == randomList[2] || randomList[2] == randomList[1])
    {
        winningAmount = gil * 2;
    }
    else
    {
        winningAmount = 0;
    }
    Console.WriteLine("Winning amount is {0} ", winningAmount);
}

补充:Dice方法的随机数生成逻辑无同类问题,可正常运行。


内容的提问来源于stack exchange,提问作者MutablePig

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.29 20:24:05