C#命令行骰子程序如何识别Throw(x)、Stat(side)等带参数的用户输入
解决方案
一、先修复Dice类的已知bug
现有Dice类存在3处逻辑错误,会导致后续功能运行报错,先修正代码:
using System; namespace Oefening_2 { class Dice { public int Sides { get; set; } private readonly Random _rnd = new Random(); public int[] Thrown; public Dice(int sides) { Sides = sides; // 修正:数组长度设置为sides+1,索引1~sides对应1~sides面的统计数据,避免越界 Thrown = new int[sides + 1]; } public Dice():this(6) { } public int Throw() { // 修正:Next上限加1,才能生成包含最大面数的随机值 int thrownNumber = _rnd.Next(1, Sides + 1); Thrown[thrownNumber]++; return thrownNumber; } public int NrOfTimesThrown(int side) { // 新增参数合法性校验 if(side < 1 || side > Sides) { return -1; // 返回-1代表参数非法 } return Thrown[side]; } public void ResetStatistics() { // 修正:遍历范围改为1~Sides for(int i = 1 ; i <= Sides; i++) { Thrown[i] = 0; } } } }
二、实现带参数指令的解析逻辑
核心思路是对输入字符串做特征匹配,拆分指令名和括号内的参数,增加合法性校验,修改后的MainIO方法代码如下:
static void MainIO(Dice CurrentDice) { Console.Write("Input: "); string input = Console.ReadLine()?.Trim() ?? string.Empty; // 单次投掷 if (input.Equals("Throw", StringComparison.OrdinalIgnoreCase)) { Console.WriteLine(CurrentDice.Throw()); } // 多次投掷 Throw(x) else if (input.StartsWith("Throw(", StringComparison.OrdinalIgnoreCase) && input.EndsWith(")")) { // 截取括号内的参数 string paramStr = input.Substring(6, input.Length - 7).Trim(); if (int.TryParse(paramStr, out int throwTimes) && throwTimes > 0) { for (int i = 0; i < throwTimes; i++) { Console.WriteLine($"第{i+1}次投掷结果:{CurrentDice.Throw()}"); } } else { Console.WriteLine("参数错误,请输入正整数,示例:Throw(5)"); } } // 查询统计 Stat(side) else if (input.StartsWith("Stat(", StringComparison.OrdinalIgnoreCase) && input.EndsWith(")")) { string paramStr = input.Substring(5, input.Length - 6).Trim(); if (int.TryParse(paramStr, out int side)) { int count = CurrentDice.NrOfTimesThrown(side); if (count == -1) { Console.WriteLine($"参数错误,骰子仅1~{CurrentDice.Sides}面"); } else { Console.WriteLine($"{side}面累计投掷次数:{count}"); } } else { Console.WriteLine("参数错误,请输入要查询的面数,示例:Stat(3)"); } } // 重置统计 else if (input.Equals("Reset", StringComparison.OrdinalIgnoreCase)) { CurrentDice.ResetStatistics(); Console.WriteLine("统计数据已重置"); } // 非法输入提示 else { Console.WriteLine("未识别的指令,请按照提示输入合法指令"); } // 递归调用保持程序运行 MainIO(CurrentDice); }
补充说明
- 代码新增了大小写不敏感匹配,用户输入throw、THROW都可以正常识别
- 所有带参数的指令都增加了合法性校验,避免非法输入导致程序崩溃
- 每个操作都增加了对应提示,用户可以直观看到操作结果
内容的提问来源于stack exchange,提问作者Tom4045
相关产品推荐
相关产品推荐

