C# 使用者輸入
獲取使用者輸入
您已經學過 Console.WriteLine()
用於輸出(列印)值。現在我們將使用 Console.ReadLine()
來獲取使用者輸入。
在下面的示例中,使用者可以輸入他們的使用者名稱,該使用者名稱儲存在變數 userName
中。然後我們列印 userName
的值。
示例
// Type your username and press enter
Console.WriteLine("Enter username:");
// Create a string variable and get user input from the keyboard and store it in the variable
string userName = Console.ReadLine();
// Print the value of the variable (userName), which will display the input value
Console.WriteLine("Username is: " + userName);
使用者輸入和數字
Console.ReadLine()
方法返回一個 string
。因此,您無法從其他資料型別(如 int
)獲取資訊。以下程式將導致錯誤。
示例
Console.WriteLine("Enter your age:");
int age = Console.ReadLine();
Console.WriteLine("Your age is: " + age);
錯誤訊息將類似如下內容
無法隱式將型別“string”轉換為“int”
正如錯誤訊息所示,您不能隱式地將型別“string”轉換為“int”。
幸運的是,您在 上一章(型別轉換) 中已經學過,您可以使用 Convert.To
方法之一顯式地轉換任何型別。
示例
Console.WriteLine("Enter your age:");
int age = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Your age is: " + age);
注意:如果您輸入了錯誤的資訊(例如,在數字輸入中輸入文字),您將收到一個異常/錯誤訊息(例如 System.FormatException: “輸入字串的格式不正確。”)。
您將在後面的章節中瞭解更多關於 異常 以及如何處理錯誤的資訊。