[英]C# How can I make an exception to allow only numbers?
這是我的代碼
Console.WriteLine("Do you want to: 1. play against an Ai or 2. let two Ai´s play aigainst each other?");
Console.WriteLine("Please choose one option!");
int userInput = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("\n");
if (userInput == 1)
{
// Player
Player player = new Player();
我試圖制作一個 try catch 塊,但后來我的if
語句中的userInput
總是出現問題。 我想要一個try.. catch
塊來確保,如果用戶輸入 char 或其他內容( +
、 ~
、 #
、...),他們會收到錯誤消息並可以輸入新內容。
我建議使用 loop 和if
而不是捕獲異常(異常是為異常情況而設計的,但事實並非如此——我們應該只驗證用戶輸入):
int userInput = -1;
// Keep on asking user until valid input is provided
while (true) {
Console.WriteLine("Do you want to:");
Console.WriteLine(" 1. play against an Ai or ");
Console.WriteLine(" 2. let two Ai´s play aigainst each other?");
Console.WriteLine("Please choose one option!");
// Trim() - let's be nice and tolerate leading and trailing spaces
string input = Console.ReadLine().Trim();
if (input == "1" || input == "2") {
userInput = int.Parse(input);
break;
}
Console.WriteLine("Sorry, invalid option. Please, try again.");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.