【问题标题】:TryParse getting annoying [closed]TryParse 变得烦人[关闭]
【发布时间】:2014-08-04 10:00:39
【问题描述】:

我遇到了这个非常烦人的问题(我知道这是基本的东西)但是当我尝试使用 tryparse 时,我必须在它说整数之前输入 2 个值,我希望它在 1 次尝试后说整数。 (顺便说一句,我必须使用 tryparse) 这是一个例子。

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int results = 0;

            Console.WriteLine("how old are you?");
            int.TryParse (Console.ReadLine(), out results);

            if (int.TryParse (Console.ReadLine(), out results))
            {
                Console.WriteLine("integer");                 
            }     
            else
            {
                Console.WriteLine("not an integer");     
            }
            Console.ReadLine();      
        }
    }
}

【问题讨论】:

  • 使用变量string input = Console.ReadLine();
  • 你的代码完全按照你的要求去做。

标签: c# tryparse


【解决方案1】:

摆脱对TryParse的第一个冗余调用,例如

class Program
{
    static void Main(string[] args)
    {
        int results = 0;

        Console.WriteLine("how old are you?");

        //int.TryParse(Console.ReadLine(), out results); <-- remove this

        if (int.TryParse (Console.ReadLine(), out results))
        {
            Console.WriteLine("integer");
        }
        else
        {
            Console.WriteLine("not an integer");
        }

        Console.ReadLine();
    }
}

【讨论】:

    【解决方案2】:

    Console.ReadLine()int.TryParse 使用变量:

    Console.WriteLine("how old are you?");
    string input = Console.ReadLine().Trim();
    bool success = int.TryParse(input, out results);
    
    if ( success )
    {
        Console.WriteLine("{0} is an integer", input); // results has the correct value                
    }
    else
    {
        Console.WriteLine("{0} is not an integer", input);                 
    }
    

    【讨论】:

      【解决方案3】:

      Int32.TryParse 将数字的字符串表示形式转换为其等效的 32 位有符号整数。

      返回值表示转换是否成功。

      所以你可以一直这样使用它。

      if (int.TryParse (Console.ReadLine(), out results))
      {
          Console.WriteLine("integer");
      }
      

      【讨论】:

        【解决方案4】:

        除了其他答案之外,您可能希望在 while loop 中执行 TryParse,以便用户必须输入有效整数

        while(!int.TryParse(ConsoleReadLine(), out results)
             Console.WriteLine("not an integer");
        
        ConsoleWriteLine("integer");
        

        为了更好地解释您当前的问题,您要求用户输入两个整数,但您只关心第二个整数。第一个分配给results,但下次您调用TryParse 时它会被覆盖而从未使用过

        【讨论】:

          猜你喜欢
          • 2014-05-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2010-10-01
          • 2014-12-14
          • 1970-01-01
          • 2017-03-06
          相关资源
          最近更新 更多