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

C#如何在while循环中通过用户输入向List添加符合总值限制的对象

实现方案

你的思路用while循环实现是正确的,核心要注意先校验再添加:不要先把对象加入列表再算总和,而是在创建对象、加入列表之前,先判断当前累计值加上新行的数值是否会超过上限,不超限才执行添加操作,避免额外的回滚删除逻辑。

修正后可直接运行的代码

public class Row
{
    public string ID { get; set; }
    public int Value { get; set; }

    public Row(string id, int rowValue)
    {
        ID = id;
        Value = rowValue;
    }
}

public class Program
{
    static void Main(string[] args)
    {
        List<Row> rows = new List<Row>();
        int TOTAL = 0;
        int maxTotal = 100;
        
        // 累计值未达上限时持续允许录入
        while (TOTAL < maxTotal)
        {
            Console.Write("Insert row ID: ");
            string id = Console.ReadLine()?.Trim();
            // 输入空ID直接退出录入流程
            if (string.IsNullOrEmpty(id))
            {
                break;
            }

            Console.Write("Insert row value: ");
            // 校验输入是否为合法非负整数
            if (!int.TryParse(Console.ReadLine(), out int rowValue) || rowValue < 0)
            {
                Console.WriteLine("输入无效,请输入非负整数,重新录入当前行");
                continue;
            }

            // 预判添加后是否超限
            if (TOTAL + rowValue > maxTotal)
            {
                Console.WriteLine($"添加失败:当前累计值{TOTAL},加入本行后总值为{TOTAL + rowValue},超过上限{maxTotal}");
                // 如果超限后直接终止录入,把下面的continue换成break即可
                continue;
            }

            // 所有校验通过才添加对象到列表
            rows.Add(new Row(id, rowValue));
            TOTAL += rowValue;
            Console.WriteLine($"添加成功,当前累计值:{TOTAL}");
        }

        // 输出最终结果
        Console.WriteLine("\n=== 已录入的行数据 ===");
        foreach (var row in rows)
        {
            Console.WriteLine($"{row.ID} {row.Value}");
        }
        Console.WriteLine($"累计总值:{TOTAL}/{maxTotal}");
    }
}

关键逻辑说明

  • 循环条件使用TOTAL < maxTotal:当累计值已经等于上限时,任何正数值的新行都会导致超限,无需继续循环
  • 提前做输入合法性校验,避免用户输入非数字、负数导致程序逻辑异常
  • 超限后的行为可按需调整:如果需要直接终止录入,把超限判断分支里的continue替换为break即可;如果需要允许用户重新输入符合条件的数值,保留continue即可
  • 移除了原代码中硬编码写死的row2、row3,所有行都通过用户交互录入,和第一行的录入逻辑保持一致

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 07:39:20