【问题标题】:How can I validate console input as integers?如何将控制台输入验证为整数?
【发布时间】:2011-06-15 20:29:05
【问题描述】:

我已经编写了我的代码,我想以这样的方式验证它,它只允许输入整数而不是字母。这是代码,请我爱你帮助我。谢谢。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace minimum
{
    class Program
    {
        static void Main(string[] args)
        {
            int a = Convert.ToInt32(Console.ReadLine());
            int b = Convert.ToInt32(Console.ReadLine());
            int c = Convert.ToInt32(Console.ReadLine());

            if (a < b)
            {
                if (a < c)
                {
                    Console.WriteLine(a + "is the minimum number");
                }
            }
            if (b < a)
            {
                if (b < c)
                {
                    Console.WriteLine(b + "is the minimum number");
                }
            }
            if (c < a)
            {
                if (c < b)
                {
                    Console.WriteLine(c + "is the minimum number");
                }
            }


            Console.ReadLine();
        }
    }
}

【问题讨论】:

    标签: c# validation console


    【解决方案1】:
    var getInput=Console.ReadLine();
        int option;        
        //validating input
            while(!int.TryParse(getInput, out option))
            {
                Console.WriteLine("Incorrect input type. Please try again");
                getInput=Console.ReadLine();
            } 
    

    【讨论】:

      【解决方案2】:
              string Temp;
              int tempInt,a;
              bool result=false;
              while ( result == false )
                  {
                  Console.Write ("\n Enter A Number : ");
                  Temp = Console.ReadLine ();
                  result = int.TryParse (Temp, out tempInt);
                  if ( result == false )
                      {
                      Console.Write ("\n Please Enter Numbers Only.");
                      }
                  else
                      {
                      a=tempInt;
                      break;
                      }
                  }
      

      【讨论】:

        【解决方案3】:

        试试这个简单的

        try
        {
            string x= "aaa";
            Convert.ToInt16(x);
            //if success is integer not go to catch
        }
        catch
        {
            //if not integer 
            return;
        }
        

        【讨论】:

          【解决方案4】:

          双/浮动:

          我只是扩展@Hans Passant 的答案(照顾 DecimalSeparator 和“-”):

              static double ReadNumber()
              {
                  var buf = new StringBuilder();
                  for (; ; )
                  {
                      var key = Console.ReadKey(true);
                      if (key.Key == ConsoleKey.Enter && buf.Length > 0)
                      {
                          Console.WriteLine();
                          return Convert.ToDouble(buf.ToString());
                      }
                      else if (key.Key == ConsoleKey.Backspace && buf.Length > 0)
                      {
                          buf.Remove(buf.Length - 1, 1);
                          Console.Write("\b \b");
                      }
                      else if (System.Globalization.NumberFormatInfo.CurrentInfo.NumberDecimalSeparator.Contains(key.KeyChar) && buf.ToString().IndexOf(System.Globalization.NumberFormatInfo.CurrentInfo.NumberDecimalSeparator) == -1)
                      {
                          buf.Append(key.KeyChar);
                          Console.Write(key.KeyChar);
                      }
                      else if ("-".Contains(key.KeyChar) && buf.ToString().IndexOf("-") == -1 && buf.ToString() == "")
                      {
                          buf.Append(key.KeyChar);
                          Console.Write(key.KeyChar);
                      }
                      else if ("0123456789".Contains(key.KeyChar))
                      {
                          buf.Append(key.KeyChar);
                          Console.Write(key.KeyChar);
                      }
                      else
                      {
                          Console.Beep();
                      }
                  }
              }
          

          【讨论】:

            【解决方案5】:

            只需调用 Readline() 并使用 Int.TryParse 循环,直到用户输入有效数字:)

            int X;
            
            String Result = Console.ReadLine();
            
            while(!Int32.TryParse(Result, out X))
            {
               Console.WriteLine("Not a valid number, try again.");
            
               Result = Console.ReadLine();
            }
            

            希望有帮助

            【讨论】:

              【解决方案6】:

              要让控制台过滤掉按字母顺序排列的击键,您必须接管输入解析。 Console.ReadKey() 方法对此至关重要,它可以让您嗅探按下的键。这是一个示例实现:

                  static string ReadNumber() {
                      var buf = new StringBuilder();
                      for (; ; ) {
                          var key = Console.ReadKey(true);
                          if (key.Key == ConsoleKey.Enter && buf.Length > 0) {
                              return buf.ToString() ;
                          }
                          else if (key.Key == ConsoleKey.Backspace && buf.Length > 0) {
                              buf.Remove(buf.Length-1, 1);
                              Console.Write("\b \b");
                          }
                          else if ("0123456789.-".Contains(key.KeyChar)) {
                              buf.Append(key.KeyChar);
                              Console.Write(key.KeyChar);
                          }
                          else {
                              Console.Beep();
                          }
                      }
                  }
              

              您可以在检测 Enter 键的 if() 语句中添加例如 Decimal.TryParse() 以验证输入的字符串是否仍然是有效数字。这样你就可以拒绝像“1-2”这样的输入。

              【讨论】:

              • +1 但您可能应该验证修饰符:-) (Ctrl, Alt...)
              • 确实如此。让我们称之为功能:)
              【解决方案7】:

              我的首选解决方案是:

              static void Main()
              {
                  Console.WriteLine(
                      (
                          from line in Generate(()=>Console.ReadLine()).Take(3)
                          let val = ParseAsInt(line)
                          where val.HasValue
                          select val.Value
                      ).Min()
                  );
              }
              static IEnumerable<T> Generate<T>(Func<T> generator) { 
                 while(true) yield return generator(); 
              }
              static int? ParseAsInt(string str) {
                 int retval; 
                 return int.TryParse(str,out retval) ? retval : default(int?); 
              }
              

              当然,根据规范(是否应该重试无效号码?),可能需要调整。

              【讨论】:

              • 密码?拼图?嗯,这不好:-) - 我打算使功能组合并避免使用大型函数 - 我想生成函数需要一点时间来适应......
              【解决方案8】:

              注意

              if (a < b) {
                  if (a < c) {
              

              等价于

              if (a < b && a < c) {
              

              并且后一种形式引入了更少的嵌套并且更具可读性,尤其是当您的代码变得更加复杂时。此外,您可能永远不要使用Convert.ToInt32 - 它有一个特别糟糕和令人惊讶的极端情况;而且它的类型安全性也低于int.Parse,这是可能的最佳选择 - 或者当您不确定字符串是否有效时int.TryParse。基本上,尽可能避免Convert....

              【讨论】:

                【解决方案9】:

                不要立即转换用户的输入。将它放在一个字符串中并使用 Int32.TryParse(...) 来确定是否输入了一个数字。像这样:

                int i;
                string input = Console.ReadLine();
                if(Int32.TryParse(input, out i))
                {
                    // it is a number and it is stored in i
                }
                else
                {
                    // it is not a number
                }
                

                【讨论】:

                • 哇,这是同时包含所有这些解决方案的记录吗?我们应该删除它们吗?
                【解决方案10】:

                您应该测试它是否是 int 而不是立即转换。 尝试类似:

                string line = Console.ReadLine();
                int value;
                if (int.TryParse(line, out value))
                {
                   // this is an int
                   // do you minimum number check here
                }
                else
                {
                   // this is not an int
                }
                

                【讨论】:

                  猜你喜欢
                  • 2018-03-09
                  • 1970-01-01
                  • 1970-01-01
                  • 2021-09-18
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  相关资源
                  最近更新 更多