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

公交模拟器添加乘客时异常处理导致性别值未正确存储问题

问题分析与解决方案

问题描述

开发公交模拟器时,添加乘客功能存在两个问题:

  • 性别输入触发异常(比如误按回车)后,后续输入的性别无法正确保存到目标Passenger对象中,例如输入回车后再输入1(男性)、年龄23、目的地5,最终显示性别为0而非预期的1。
  • 希望获得更优的输入重试实现方式,避免当前代码的冗余与逻辑漏洞。

原代码

添加乘客方法

public void add_Passenger()
{
    Console.WriteLine("You've chosen to add passenger.Start with gender, type 1 for male and 2 for female.");
    var passenger = new Passenger();
   
    try 
    {
        int gender = int.Parse(Console.ReadLine());
        do
        {
            if (gender == 1 | gender == 2)
            {
                passenger.Gender = gender;
            }
            else
            {
                Console.WriteLine("Incorrect choice, try again!.");
                gender = int.Parse(Console.ReadLine());
            }
        } while (gender >= 3);
    }
    catch (Exception)
    {
          Console.WriteLine("Incorrect input, try again!");
          ChooseTheGender();
    }

    
    Console.WriteLine("Now enter the passengers age.");
    passenger.Age = int.Parse(Console.ReadLine());
    Console.WriteLine("Now enter the passengers destination in numbers.");
    passenger.Destination = int.Parse(Console.ReadLine());
    passengers_list.Add(passenger);
}

性别选择方法

public static void ChooseTheGender()
{
    var Passenger = new Passenger();
    int gender = int.Parse(Console.ReadLine());
    try
    {
        
        do
        {
            if (gender == 1 | gender == 2)
            {
                Passenger.Gender = gender;
            }
            else
            {
                Console.WriteLine("Ogiltlig val! Försök igen.");
                gender = int.Parse(Console.ReadLine());
            }
        } while (gender != 1 && gender != 2);
    }
    catch (Exception)
    {
        Console.WriteLine("Ogiltlig input, försök igen!");
        ChooseTheGender();
    }
}

问题根源

  1. 对象不匹配:ChooseTheGender方法中新建了独立的Passenger对象,赋值的性别仅保存在这个临时对象中,和add_Passenger里的目标passenger对象无关联,导致原对象性别仍为默认值0。
  2. 递归风险:异常时递归调用ChooseTheGender,多次重试可能引发栈溢出。
  3. 异常处理冗余:同时使用try-catch和循环验证,逻辑重复且效率低。
  4. 输入验证漏洞:原循环条件gender >=3无法覆盖负数等非法值。

优化方案

核心改进点

  • 将性别选择改为返回合法数值的方法,直接为目标对象赋值,避免对象不匹配问题。
  • 使用int.TryParse替代int.Parse,无需捕获异常即可判断输入合法性,性能更优。
  • 用循环代替递归实现重试,避免栈溢出风险。
  • 统一输入验证逻辑,覆盖所有非法输入场景(非数字、超出有效范围)。

重构后的代码

通用输入验证方法(可复用)

// 通用方法:获取指定范围内的整数输入
private int GetValidIntInput(string prompt, int min, int max)
{
    int input;
    bool isValid;
    do
    {
        Console.WriteLine(prompt);
        string inputStr = Console.ReadLine().Trim();
        isValid = int.TryParse(inputStr, out input) && input >= min && input <= max;
        if (!isValid)
        {
            Console.WriteLine($"输入无效,请输入{min}到{max}之间的整数!");
        }
    } while (!isValid);
    return input;
}

重构后的添加乘客方法

public void AddPassenger()
{
    var passenger = new Passenger();
    
    // 获取合法性别输入
    string genderPrompt = "请选择乘客性别:1=男性,2=女性";
    passenger.Gender = GetValidIntInput(genderPrompt, 1, 2);
    
    // 获取合法年龄输入(假设年龄范围1-120)
    string agePrompt = "请输入乘客年龄";
    passenger.Age = GetValidIntInput(agePrompt, 1, 120);
    
    // 获取合法目的地输入(假设目的地编号1-10)
    string destPrompt = "请输入乘客目的地编号(数字)";
    passenger.Destination = GetValidIntInput(destPrompt, 1, 10);
    
    passengers_list.Add(passenger);
}

说明

  • 通用的GetValidIntInput方法可复用在所有需要整数输入的场景,大幅减少代码冗余。
  • 输入验证覆盖了非数字、超出范围的所有非法情况,无需额外异常捕获。
  • 所有输入直接赋值给目标passenger对象,彻底解决性别保存失败的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 04:52:49