我如何可以验证控制台输入为整数? [英] How can I validate console input as integers?

查看:97
本文介绍了我如何可以验证控制台输入为整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写我的codeS,我想验证它以这样一种方式泰德只会允许inputed intergers而不是字母。这里是code,请我会爱你帮助我。谢谢你。

 使用系统;
使用System.Collections.Generic;
使用System.Linq的;
使用System.Text;命名空间最小
{
    类节目
    {
        静态无效的主要(字串[] args)
        {
            INT A = Convert.ToInt32(到Console.ReadLine());
            INT B = Convert.ToInt32(到Console.ReadLine());
            INT C = Convert.ToInt32(到Console.ReadLine());            如果(A< B)
            {
                如果(一个c为C)
                {
                    Console.WriteLine(A +是最小数目);
                }
            }
            如果(B<一)
            {
                如果(B< c)
                {
                    Console.WriteLine(B +是最小数目);
                }
            }
            如果(℃下一个)
            {
                如果(℃下; B)
                {
                    Console.WriteLine(C +是最小数目);
                }
            }
            到Console.ReadLine();
        }
    }
}


解决方案

您应该测试,如果它是一个int,而不是马上转换。
尝试是这样的:

 串线=到Console.ReadLine();
int值;
如果(int.TryParse(线,超时值))
{
   //这是一个int
   //这里做你的最小号检查
}
其他
{
   //这不是一个int
}

I have written my codes and i want to validate it in such a way thet it will only allow intergers to be inputed and not alphabets. Here is the code, please I will love you to help me. Thanks.

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();
        }
    }
}

解决方案

You should test if it's an int instead of converting in right away. Try something like :

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
}

这篇关于我如何可以验证控制台输入为整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆