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

C#方法传参及字符串转int时抛出System.FormatException问题求助

异常触发原因

你当前代码触发System.FormatException的核心原因是你传入ConvertToInt方法的字符串永远是初始定义的"{C} ",该字符串不符合整数格式,无法完成转换,具体代码逻辑问题如下:

  • GetUserInput方法内部逻辑写反:你先通过Console.ReadLine()获取了用户输入的分数存到score变量,紧接着执行score = scores,用传入的初始值直接覆盖了用户输入,最终返回的也是被覆盖后的错误值
  • Main方法没有接收GetUserInput的返回值:你调用完GetUserInput方法后直接丢弃了返回结果,还是用初始的"{C} "字符串去执行类型转换,必然触发格式异常
  • 缺少输入合法性校验:直接用Convert.ToInt32转换用户输入,一旦用户输入非数字内容必然抛异常,建议用更安全的int.TryParse方法处理
修复后完整代码(支持循环输入任意数量分数)
using System;
using System.Collections.Generic;

namespace MethodsAndUnitTestsMethodTestsCampbell
{
    class Program
    {
        // 获取用户输入的方法
        private static string GetUserInput()
        {
            Console.Write("Enter score (enter 'q' to exit): ");
            return Console.ReadLine().Trim();
        }

        // 安全转换为整数的方法,转换成功返回true,out参数返回转换后的分数
        private static bool TryConvertToInt(string input, out int score)
        {
            return int.TryParse(input, out score);
        }

        static void Main(string[] args)
        {
            List<int> allScores = new List<int>();
            while (true)
            {
                string input = GetUserInput();
                // 输入q就退出循环
                if (input.Equals("q", StringComparison.OrdinalIgnoreCase))
                {
                    break;
                }
                if (TryConvertToInt(input, out int score))
                {
                    allScores.Add(score);
                    Console.WriteLine($"Score {score} added successfully");
                }
                else
                {
                    Console.WriteLine("Invalid input, please enter a valid integer or 'q' to exit");
                }
            }
            // 输出所有录入的分数
            Console.WriteLine("\nAll scores you entered:");
            foreach (int s in allScores)
            {
                Console.Write(s + " ");
            }
        }
    }
}
逻辑说明
  • 移除了GetUserInput方法无用的入参,直接返回用户输入的原始内容
  • 替换Convert.ToInt32为int.TryParse做安全转换,避免非法输入触发异常
  • 新增循环逻辑,支持用户输入任意数量分数,输入q即可结束录入
  • 新增分数存储逻辑,所有录入的合法分数都会存到List集合中方便后续处理

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 20:45:06