You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

制作C#交互式文本游戏时遭遇CLR/System.FormatException异常求助

问题分析与修复方案

核心错误点

  • 输入读取顺序完全颠倒:你在显示任何引导文本之前就执行了int decision = Convert.ToInt32(Console.ReadLine());,玩家此时看不到任何提示,根本不知道该输入什么;如果玩家输入非数字内容,Convert.ToInt32会直接抛出System.FormatException。
  • 冗余的输入等待:显示引导文本后额外添加的Console.ReadLine()会让玩家需要多次回车才能继续,完全打乱了交互逻辑。
  • 无输入合法性校验:没有处理玩家输入非1/2或非数字的情况,程序容错性极差。

修复后的代码

using System;

namespace Coding_basics
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Title = "To Infinity";
            Console.ForegroundColor = ConsoleColor.Green;

            // 先显示所有引导提示,再读取输入
            Console.WriteLine("Welcome");
            Console.WriteLine("You have entered the program, press 1 to proceed or press 2 to leave");

            // 用TryParse替代Convert.ToInt32,避免异常并校验输入有效性
            string input = Console.ReadLine();
            if (int.TryParse(input, out int decision))
            {
                if (decision == 1)
                {
                    Console.WriteLine("Good luck...");
                }
                else if (decision == 2)
                {
                    Environment.Exit(0);
                }
                else
                {
                    Console.WriteLine("Invalid input, please enter 1 or 2");
                }
            }
            else
            {
                Console.WriteLine("Please enter a valid number");
            }

            Console.ReadKey();
        }
    }
}

修复说明

  • 调整交互顺序:先展示引导文本,再读取玩家输入,符合正常游戏交互逻辑。
  • 替换输入转换方式:使用int.TryParse替代Convert.ToInt32,既可以完成字符串转整数的操作,又能在输入非数字时避免抛出异常,同时返回输入是否有效。
  • 移除冗余代码:删除多余的Console.ReadLine(),简化交互流程,玩家只需一次输入即可完成选择。
  • 增加异常输入处理:针对玩家输入非1/2的数字、非数字内容的情况,给出明确的错误提示,提升程序健壮性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 22:55:29