簡體   English   中英

為什么第一次嘗試時不顯示錯誤消息,但在另一個嘗試時工作正常?

[英]Why does the error message not show for the first try, but works fine for the other?

有人可以告訴我為什么當用戶輸入無效格式的數據時第一次嘗試捕獲沒有顯示錯誤消息,即輸入整數而不是字符串。 如果我輸入數字而不是字母,程序只會接受它並繼續前進。 另一個針對年齡的嘗試運行良好。

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);
    }

第一個 try/catch 塊也正常工作。 由開發人員決定一個字符串可以包含什么值以使其有效或無效。

就語言而言,“john doe”和“123151”都是有效的字符串(第二個只是數字的字符串表示形式)。 請記住,代碼對這兩者的解釋非常不同:

  1. “123151”
  2. 123151

第一個是值為“123151”的字符串。 第二個是 integer,值為 123151。

當您從 console.ReadLine() function 讀取到字符串變量時,您將獲得輸入的任何值的字符串值。

我的建議是,繼續前進,您添加某種編程來驗證輸入的值是否更像您的程序所期望的值。 例如,如果您不希望字符串中包含任何數字,則可以檢查字符串中的 integer 值,如果發現則拋出異常。 您甚至可以使用正則表達式來幫助識別整數或其他無效值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM