SIMI
SIMI

Reputation: 109

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

Upvotes: 10

Views: 80539

Answers (10)

bhat
bhat

Reputation: 11

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

Upvotes: 0

Sushrut Bhosale
Sushrut Bhosale

Reputation: 35

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

Upvotes: 1

Try This Simple

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

Upvotes: -1

user3550499
user3550499

Reputation: 31

Double/Float:

I'm just extending @Hans Passant answer (Taking care of DecimalSeparator and "-"):

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

Upvotes: 0

Machinarius
Machinarius

Reputation: 3731

Simply call Readline() and loop with Int.TryParse until the user inputs a valid number :)

int X;

String Result = Console.ReadLine();

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

   Result = Console.ReadLine();
}

Hope that helps

Upvotes: 11

Hans Passant
Hans Passant

Reputation: 941277

To get the console to filter out alphabetical keystrokes you have to take over input parsing. The Console.ReadKey() method is fundamental to this, it lets you sniff the pressed key. Here's a sample implementation:

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

You could add, say, Decimal.TryParse() in the if() statement that detects the Enter key to verify that the entered string is still a valid number. That way you can reject input like "1-2".

Upvotes: 9

Eamon Nerbonne
Eamon Nerbonne

Reputation: 48066

My preferred solution would be:

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

Of course, depending on the specification (should invalid number be retried?), it may need to be tweaked.

Upvotes: 0

Eamon Nerbonne
Eamon Nerbonne

Reputation: 48066

Note that

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

is equivalent to

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

and that this latter form introduces less nesting and is more readable, particularly if your code grows more complex. Also, you should probably never use Convert.ToInt32 - it has a particularly ill-conceived and surprising corner case; and it's also less type-safe than int.Parse which is the superior choice where possible - or int.TryParse when you're unsure whether the string is valid. Basically, avoid Convert.... wherever possible.

Upvotes: 1

Emond
Emond

Reputation: 50672

Do not Convert the input from the user immediately. Put it in a string and use Int32.TryParse(...) to find out whether or not a number was entered. Like this:

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
}

Upvotes: 1

zov
zov

Reputation: 4122

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
}

Upvotes: 18

Related Questions