C# Как я могу сделать исключение, чтобы разрешать только числа?

#c# #exception

Вопрос:

Вот мой код

 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, но потом userInput в моем заявлении всегда появлялась проблема if . Я хочу try .. catch , чтобы блок был уверен, что если пользователь введет символ или что-то еще ( , ~ , # ,…), они получат сообщение об ошибке и смогут ввести что-то новое.

Комментарии:

1. int.TryParse а петля ?

Ответ №1:

Я предлагаю использовать цикл и 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.");
   }
 

Комментарии:

1. Почему бы вместо этого не использовать TryParse?

2. Нечего и пытаться. Это всего лишь 1 или 2.