Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
90 views
in Technique[技术] by (71.8m points)

c# - How can I validate console input as integers?

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();
        }
    }
}
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...