如何验证控制台输入为整数?

SIM*_*IMI 9 c# validation console

我已经编写了我的代码,我想以这样的方式对其进行验证,它只允许插入内容而不是字母.这是代码,请你帮助我.谢谢.

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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

zov*_*zov 15

您应该测试它是否为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
}
Run Code Online (Sandbox Code Playgroud)


Mac*_*ius 10

只需调用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();
}
Run Code Online (Sandbox Code Playgroud)

希望有所帮助


Han*_*ant 9

要让控制台过滤掉按字母顺序排列的键击,您必须接管输入解析.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();
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

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