开发者

How to prevent non-numeric input in VB.NET?

I'm working on a program that requires the user to input an integer. How do I prevent the user from enter开发者_JAVA百科ing a non-numeric value? I tried using the IsNumeric() function but I get an error before I can use it. I get the error at the console.read, before I can call the IsNumeric() function. Here is my code:

Dim num As Integer

    Console.Write("enter num:")
    num = Console.ReadLine 

    If IsNumeric(num) = True Then
        Console.WriteLine("valid. num = " & num)
    Else
        Console.WriteLine("invalid")
    End If

Any help is greatly appreciated.


Try this:

Dim num As Integer

Console.Write("enter num:")
Dim input = Console.ReadLine

If Integer.TryParse(input, num) Then
    Console.WriteLine("valid. num = " & num)
Else
    Console.WriteLine("invalid")
End If


This is exactly the situation that Integer.TryParse() is designed for. TryParse will return false if the string you test can't be converted into an integer.


Rather try something like:

Dim num as Integer
Console.Write("Enter num: ")

While (Not (Integer.TryParse(num, Console.ReadLine())))
    Console.WriteLine("Please enter an Integer only: ")
End While

The TryParse method tries to parse the input value and returns a false when the value couldn't be parsed to the said type. The above code will ask the used for input until they enter an integer.


You could read a string, then attempt to convert it into the integer. Trap any exceptions produced by the conversion, to handle non-numeric input.


In C# sorry...

using System;
    class Program
    {
        static void Main(string[] args)
        {
            int a = GetNumericInput();
            Console.WriteLine("Success, number {0} entered!",a);
            Console.Read();
        }

        private static int GetNumericInput()
        {
            int number;
            string input;
            bool first = true;
            do
            {
                if (!first)
                {
                    Console.WriteLine("Invalid Number, try again");
                }
                Console.WriteLine("enter a number");
                input = Console.ReadLine();
                first = false;
            } while (!int.TryParse(input, out number));
            return number;
        }
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜