【问题标题】:C# How can I make an exception to allow only numbers?C#如何例外,只允许数字?
【发布时间】:2021-08-21 21:29:17
【问题描述】:

这是我的代码

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 块来确保,如果用户输入一个字符或其他东西(+,~,#,...)他们会收到一个错误消息并且可以输入新内容。

【问题讨论】:

  • int.TryParse 和一个循环?

标签: c# exception


【解决方案1】:

我建议使用循环和if 而不是捕获异常(异常是为 exception 情况而设计的,但不是这种情况 - 我们应该只验证用户输入) :

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

【讨论】:

  • 为什么不改用 TryParse?
  • 没什么可尝试的。它只有 1 或 2 个。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-10-07
  • 1970-01-01
  • 2021-02-07
  • 1970-01-01
  • 2017-07-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多