【问题标题】:Number guessing game using TryParse使用 TryParse 的猜数游戏
【发布时间】:2019-10-09 19:20:19
【问题描述】:

我在使用 TryParse 捕获用户在哪里输入字符串而不是 int 时无法让我的代码正常工作。如果我按照现在的样子使用它,如果输入了 int 以外的内容,我只会得到 0 的基值。我希望它向用户显示一条错误消息。

尝试过使用 TryParse 的多种不同方式,但都没有真正有用。

    static void Main(string[] args)
    {

        Random r = new Random();
        int speltal = r.Next(1,21);
        bool play = false;
        int myNum;

        while (!play)
        {
            Console.Write("\n\tGuess a number between 1 and 20: ");
            Int32.TryParse(Console.ReadLine(), out myNum);

            if (myNum < guessNum)
            {
                Console.WriteLine("\tThe number you have guessed is to low");
                Console.ReadLine();
            }

            if (myNum > guessNum)
            {
                Console.WriteLine("\tThe number you have guessed is to high");
                Console.ReadLine();
            }

            if (myNum == guessNum)
            {
                Console.WriteLine("\tCongratulations you guessed the right number!");
                Console.ReadLine();
            }

我希望它在用户输入除 int 以外的任何内容时向用户显示错误消息。根据我的老师,它还必须包含 TryParse

【问题讨论】:

  • TryParse() 如果成功则返回 true,如果失败则返回 false。不要忽略返回值,而是执行if (!Int32.TryParse(Console.ReadLine(), out myNum)) { /* report error */ } else { /* do whatever else */ } 之类的操作。 They document these things,你知道的。

标签: c# tryparse


【解决方案1】:

您没有捕获TryParsebool 输出,因此您不知道是否输入了非数字值。试试这样的:

bool isValid;
do
{
     Console.Write("\n\tGuess a number between 1 and 20: ");
     isValid = Int32.TryParse(Console.ReadLine(), out myNum);
     if(!isValid)
     {
         Console.WriteLine("\n\tInvalid input detected. Please try again.");
     }
} while(!isValid)

【讨论】:

    【解决方案2】:

    TryParse 方法只能将整数放入传递的变量中(因为它是int 类型),所以如果传递给它的值无法解析成整数,则默认值为int (0) 将分配给变量。

    TryParse 告诉你它是否成功解析数字的方式是返回一个布尔指示符。

    你可以试试这个:

    while (true)
    {
        bool valid = int.TryParse(Console.ReadLine(), out myNum);
        if(valid)
            break;
        Console.WriteLine("Input invalid. Please try again");
    }
    

    【讨论】:

      【解决方案3】:

      TryParse 返回一个布尔值,指示输入字符串是否成功解析。关于如何处理无效输入,上述两个答案都是正确的,但这里有一个更简洁的版本,它也将支持 规则between 1 and 20:

      while (true)
      {    
          Console.Write("\n\tGuess a number between 1 and 20: ");
      
          //Checks to see if the input was successfully parsed to a integer also, performs a Trim on the input as to remove any accidental white spaces that a user might have typed in, e.g. "1000 "
          if (int.TryParse(Console.ReadLine().Trim(), out myNum))
          {
              //Checks to see if the parsed number is in the specified range
              if ((myNum > 0) && (myNum < 21))
              {
                  break;
              }
              Console.WriteLine("\tThe input number was out of the specified range.");
          }
          else
          {
              Console.WriteLine("\tFailed to parse the input text.");
          }
          //Optional, makes the thread sleep so the user has the time to read the error message.
          Thread.Sleep(1500);
      
          //Optional, clears the console as to not create duplicates of the error message and the value of Console.Write
          Console.Clear();
      }
      
      // Continue here, if (myNum < guessNum) . . .
      

      【讨论】:

        【解决方案4】:

        您应该使用TryParse 返回的bool。看起来像这样的东西:

        更新答案:

                static void Main(string[] args)
                {
                    Random random = new Random();
                    int guessNum = random.Next(1, 21);
        
                    while(true)
                    {
                        Console.WriteLine("Guess the number between 1 and 21.");
        
                        if (Int32.TryParse(Console.ReadLine(), out int input))
                        {
                            if (input == guessNum)
                            {
                                Console.WriteLine($"You guessed it right. The number is {input}");
                                if(ShouldContinue())
                                {
                                    guessNum = random.Next();
                                    continue;
                                }
                                else
                                {
                                    break;
                                }
                            }
        
                            if (input < guessNum)
                                Console.WriteLine("The number you guessed is smaller.");
                            else
                                Console.WriteLine("The number you guessed is bigger");
        
                        }
                        else
                        {
                            Console.WriteLine("Please enter a number between 1 and 21 as your guess");
                        }
                    }
                }
        
                static bool ShouldContinue()
                {
                    while (true)
                    {
                        Console.WriteLine($"Do you want to continue playing? (y/n)");
                        string continueInput = Console.ReadLine().Trim().ToLower();
                        if (continueInput == "y")
                            return true;
                        else if (continueInput == "n")
                            return false;
                        else
                            Console.WriteLine("Invalid input!. Please choose 'y' or 'n'.");
                    }
                }
        

        旧答案:

        while (true)
        {
            if (Int32.TryParse(inputInt, out int myNum))
            {
               // your logic goes here, too low/high or correct answer.   
            }
        }
        

        【讨论】:

        • 你没有展示如何退出无限循环。此外,这基本上是 Stanleys 答案的副本,该答案比这个早 15 分钟写成。
        猜你喜欢
        • 2021-11-20
        • 1970-01-01
        • 2016-06-21
        • 2013-10-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多