【问题标题】:Why does the error message not show for the first try, but works fine for the other?为什么第一次尝试时不显示错误消息,但在另一个尝试时工作正常?
【发布时间】:2021-06-09 15:28:01
【问题描述】:

谁能告诉我为什么当用户输入无效格式的数据时,第一次尝试捕获没有显示错误消息,即输入整数而不是字符串。如果我输入数字而不是字母,程序只会接受它并继续前进。 另一个 try catch for age 工作正常。

public void add_passenger()
    {
        // Defining variables for name and age to be input
        string name;
        int age;

        //Show message on a clean, new screen
        Console.Clear();
        Console.WriteLine("==> Welcome aboard <==");
        Console.WriteLine(" Please follow instructions to add yourself as a passenger ");
        Console.WriteLine("");
        
        // Ask user to input name
        while (true)
        {
            Console.WriteLine(" Your name: ");
            //Try and catch in case the user inputs wrong format
            try
            {
                name = Console.ReadLine();
                break;
            }
            catch //This doesn't work
            {
                Console.WriteLine(" Wrong input format. Please try again and input a rider.");
                continue;
            }
        }
        
        // Ask user to input age
        while (true)
        {
            Console.WriteLine(" Your age: ");
            //Try and catch in case the user inputs wrong format
            try
            {
                age = Convert.ToInt32(Console.ReadLine());
                break;
            }
            catch
            {
                Console.WriteLine(" Wrong input format. Please write an integer.");
                continue;
            }
        }

        // Search the array for an empty slot to input the new passenger into
        for (int i = 0; i < passengers.Length - 1; i++)
        {
            if (passengers[i] == null)
            {
                passengers[i] = new Passagerare(name, age);
                break;
            }
            else
            {
                continue;
            }
        }

        Console.WriteLine(""); 
        Console.WriteLine(" You have now boarded the bus. Welcome aboard!" );
        Console.ReadKey(true);
    }

【问题讨论】:

  • 代码行……name = Console.ReadLine();……将接受任何“包括”数字的值。数字也可以是有效的string。由于代码正在读入string 变量name,因此所有值都被接受。 name 的什么值会被视为无效值?
  • 感谢您的评论。我希望名称只能存储字母或字母,而不是数字。我想我需要为此做一些研究

标签: c# try-catch


【解决方案1】:

第一个 try/catch 块也正常工作。由开发人员决定一个字符串可以包含什么值以使其有效或无效。

就语言而言,“john doe”和“123151”都是有效的字符串(第二个只是数字的字符串表示形式)。请记住,代码对这两者的解释非常不同:

  1. “123151”
  2. 123151

第一个是值为“123151”的字符串。 第二个是整数,值为 123151。

当您从 console.ReadLine() 函数读取字符串变量时,您将获得一个字符串值,无论输入什么值。

接下来,我建议您添加某种编程来验证输入的值是否更像您的程序所期望的值。例如,如果您不希望字符串中包含任何数字,则可以检查字符串中的整数值,如果找到则抛出异常。您甚至可以使用正则表达式来帮助识别整数或其他无效值。

【讨论】:

    猜你喜欢
    • 2016-10-17
    • 1970-01-01
    • 1970-01-01
    • 2019-04-22
    • 2022-12-26
    • 1970-01-01
    • 2019-12-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多