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

C# Switch语句case2调用case1变量未赋值报错求助

解决C# Switch语句中变量未赋值的编译错误

问题背景

你的代码通过switch的case 1收集乘客数量、姓名和年龄,case 2展示这些信息,但编译器报错提示变量未初始化——因为编译器无法确保用户执行case 2前一定执行过case 1,存在变量未赋值就被使用的路径。另外当前代码还存在逻辑缺陷:只能存储最后一位乘客的信息,无法保存所有乘客数据。

根源分析

  • Giname、Gi、GiAge仅在case 1中赋值,编译器的静态检查会认为这些变量可能未初始化就被case 2调用,因此抛出错误。
  • 单个变量无法存储多个乘客的信息,当前逻辑会覆盖之前输入的乘客数据。

修复方案

方案1:给变量赋初始值+添加前置检查(快速修复)

给所有可能未初始化的变量赋初始值,同时在case 2中先判断是否已经输入过信息,避免展示空数据:

修改变量声明:

using System;

string Giname = string.Empty;
int Option, Gi = 0, Q = 0, GiAge = 0;

修改case 2的逻辑:

case 2:
    // 判断是否已输入有效信息
    if (Gi == 0 || string.IsNullOrEmpty(Giname))
    {
        Console.WriteLine("请先选择选项1输入乘客信息!");
    }
    else
    {
        Console.WriteLine("Count : {0} Person \n Name : {1} \n Age : {2} ", Gi, Giname, GiAge);
    }
    Console.WriteLine("按任意键返回菜单...");
    Console.ReadKey();
    Console.Clear();
    break;

方案2:使用类+集合存储乘客信息(更合理的长期方案)

这个方案不仅解决编译错误,还能正确存储所有乘客的信息,符合业务逻辑:

  1. 定义乘客类:
public class Passenger
{
    public string FullName { get; set; }
    public int Age { get; set; }
}
  1. 修改主代码逻辑:
using System;
using System.Collections.Generic;

int Option;
// 用集合存储所有乘客
List<Passenger> passengers = new List<Passenger>();
int passengerCount = 0;

while (true)
{
    Console.WriteLine("1-Get Info");
    Console.WriteLine("2-Show Info");
    Console.WriteLine("3-Show Trip Info");
    Console.WriteLine("4-Exit");
    Console.WriteLine("------------------");
    Console.Write("Choose you option : ");

    // 用TryParse避免输入非数字导致崩溃
    if (!int.TryParse(Console.ReadLine(), out Option))
    {
        Console.Clear();
        Console.WriteLine("输入无效,请输入数字选项!");
        continue;
    }

    Console.Clear();
    switch (Option)
    {
        case 1:
            Console.WriteLine("Please enter your information");
            Console.Write("Passenger count : ");
            if (int.TryParse(Console.ReadLine(), out passengerCount))
            {
                passengers.Clear(); // 重新输入时清空之前的记录
                for (int i = 0; i < passengerCount; i++)
                {
                    Console.WriteLine($"第{i+1}位乘客信息:");
                    Console.Write("Enter full name : ");
                    string name = Console.ReadLine();

                    Console.Write("Enter age : ");
                    if (int.TryParse(Console.ReadLine(), out int age))
                    {
                        passengers.Add(new Passenger { FullName = name, Age = age });
                    }
                    else
                    {
                        Console.WriteLine("年龄输入无效,跳过该乘客");
                    }
                }
            }
            else
            {
                Console.WriteLine("乘客数量输入无效");
            }
            Console.WriteLine("按任意键返回菜单...");
            Console.ReadKey();
            Console.Clear();
            break;
            
        case 2:
            if (passengers.Count == 0)
            {
                Console.WriteLine("请先选择选项1输入乘客信息!");
            }
            else
            {
                Console.WriteLine($"总乘客数:{passengerCount} 人\n");
                for (int i = 0; i < passengers.Count; i++)
                {
                    Console.WriteLine($"第{i+1}位:");
                    Console.WriteLine($"姓名:{passengers[i].FullName}");
                    Console.WriteLine($"年龄:{passengers[i].Age}\n");
                }
            }
            Console.WriteLine("按任意键返回菜单...");
            Console.ReadKey();
            Console.Clear();
            break;

        case 3:
            Console.WriteLine("-_-");
            Console.WriteLine("按任意键返回菜单...");
            Console.ReadKey();
            Console.Clear();
            break;

        case 4:
            Console.WriteLine("程序退出");
            return;
        default:
            Console.WriteLine("无效选项,请重新选择!");
            break;
    }
}

额外优化点

  • 使用int.TryParse替代int.Parse,避免用户输入非数字时程序崩溃。
  • 添加默认case处理无效输入。
  • 在每个case后添加按键等待,让用户能看清输出内容再返回菜单。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 00:40:04