拒绝字符串变量中的字符串

时间:2015-09-07 03:49:29

标签: c# c#-4.0 console console-application

我需要拒绝在我的控制台应用程序中编写字符串的能力,此时,当输入文本而不是数字时,控制台崩溃。

我现在有类似的东西

class Program
{
    static void Main(string[] args)
    {
        string[] names = new string[2];
        string age;
        bool agetest = false;

        Console.WriteLine("Hello, I am the NameBot2000, What is your first name?");
        names[0] = Console.ReadLine();
        Console.WriteLine("Well done. What is your surname?");
        names[1] = Console.ReadLine();
        Console.WriteLine("What year were you born in?");
        age = Console.ReadLine();

        int.Parse(age);

        if (Enumerable.Range(0,2015).Contains(age));




        int year = 0;


        string wow = "";

        if (Enumerable.Range(0,31).Contains(year))
            wow = "young";

        else if (Enumerable.Range(31,51).Contains(year)) 
            wow = "old";

        else if (Enumerable.Range(51,500).Contains(year))
            wow = "ancient";

        Console.WriteLine("Well done. You said your name was {0} {1}, and you are {2} years old!", names[0], names[1], year);
        Console.WriteLine("You are so {0}!", wow);
        Console.ReadLine();


    }
}

我试图合并一个布尔值,但我不确定如何比较变量以检查它所处的格式。

提前感谢大家!

3 个答案:

答案 0 :(得分:5)

而不是Parse,请使用TryParse

int age = 0;
if (Int32.TryParse(Console.Readline, out age)
    // Correct format.
else
    // error!

TryParse()会做什么,是用户输入,尝试解析它到int,如果成功,将输出一个int(和bool = true),否则会输出bool = false

答案 1 :(得分:0)

使用try catch

array_sum(preg_split("//", $number));

答案 2 :(得分:0)

您可以检查ConsoleKeyInfo以确保用户只能输入年龄数字。

Console.WriteLine("Enter Age : ");
ConsoleKeyInfo key;
string ageStr = "";
do
{
    key = Console.ReadKey(true);
    if (key.Key != ConsoleKey.Backspace && key.Key != ConsoleKey.Enter)
    {
        if (char.IsNumber(key.KeyChar))//Check if it is a number
        {
            ageStr += key.KeyChar;
            Console.Write(key.KeyChar);
        }
    }
    else
    {
        if (key.Key == ConsoleKey.Backspace && ageStr.Length > 0)
        {
            ageStr = ageStr.Substring(0, (ageStr.Length - 1));
            Console.Write("\b \b");
        }
    }
} 
while (key.Key != ConsoleKey.Enter);

Console.WriteLine("Age is {0}", ageStr);