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

C#控制台医院管理系统:按回车键重复显示菜单需求求助

解决方案

你的代码目前存在两个核心问题,导致无法实现需求且可能引发程序崩溃:

  • 直接用Convert.ToInt32解析用户输入,若用户按回车(输入为空)或输入非数字内容,会抛出异常导致程序崩溃。
  • 默认分支直接调用Environment.Exit(0),用户输入非1-8的内容就直接退出;继续确认环节中,用户按回车会让answer为空,循环直接终止,无法回到菜单。

以下是修改后的代码,完美解决上述问题:

public static void HospitalMenu()
{            
    string answer = "";
       
    do
    {
        Console.Clear();
        Console.WriteLine("=============Hospital Management System===================");
        Console.WriteLine("1...............Add Patient Information");
        Console.WriteLine("2...............Modify Patient Information");
        Console.WriteLine("3...............Add Patient Treatment Information");
        Console.WriteLine("4...............View Patient History");
        Console.WriteLine("5...............Search Patient Info");
        Console.WriteLine("6...............Generate Lab Report");
        Console.WriteLine("7...............Generate Medical Bills");
        Console.WriteLine("8...............Exit");

        Console.WriteLine("Select option (between 1 to 8)");
        // 用TryParse安全解析输入,避免崩溃
        if (!int.TryParse(Console.ReadLine(), out int option))
        {
            // 输入无效(含空回车),提示后重新显示菜单
            Console.WriteLine("无效输入,请按回车键重试...");
            Console.ReadLine();
            continue;
        }

        bool shouldExit = false;
        switch (option)
        {
            case 1:
                Patient.InsertPatient();
                break;
            case 2:
                Patient.UpdatePatient();
                break;
            case 3:
                PatientTreatment();
                break;
            case 4:
                ViewMenu();
                break;
            case 5:
                SearchMenu();
                break;
            case 6:
                LabMenu();
                break;
            case 7:
                BillMenu();
                break;
            case 8:
                shouldExit = true;
                break;
            default:
                // 输入超出1-8范围,提示后重新显示菜单
                Console.WriteLine("选项不在范围内,请按回车键重试...");
                Console.ReadLine();
                continue;
        }

        if (shouldExit)
        {
            break;
        }

        Console.WriteLine("是否继续?(按回车键继续,输入'n'退出)");
        answer = Console.ReadLine();
        // 空输入(按回车)视为继续,输入n/N则退出
    } while (string.IsNullOrEmpty(answer) || answer.Equals("y", StringComparison.OrdinalIgnoreCase));
}

关键改动说明:

  • 安全输入解析:用int.TryParse替代Convert.ToInt32,解析失败时不会抛出异常,仅提示错误并重新显示菜单。
  • 优化退出逻辑:仅当用户选择选项8时才触发退出,其他无效输入仅提示错误,不终止程序。
  • 适配回车需求:继续确认环节中,用户按回车(空输入)会直接回到菜单;输入n或N才会退出程序。

修改后,无论用户在哪个环节按回车,都会重复显示当前菜单,且程序不会因无效输入崩溃。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 09:27:26