为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

C#
白衣染霜花 2019-08-14 15:26:41
如何验证控制台输入为整数?我已经编写了我的代码,我想以这样的方式对其进行验证,它只允许插入内容而不是字母。这是代码,请你帮助我。谢谢。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();         }     }}
查看完整描述

3 回答

?
慕哥6287543

TA贡献1831条经验 获得超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

}


查看完整回答
反对 回复 2019-08-14
?
温温酱

TA贡献1752条经验 获得超4个赞

只需调用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();}

希望有所帮助


查看完整回答
反对 回复 2019-08-14
?
有只小跳蛙

TA贡献1824条经验 获得超8个赞

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

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


查看完整回答
反对 回复 2019-08-14
  • 3 回答
  • 0 关注
  • 492 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信