2015-09-07 63 views
2

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

我沿着这一权利的行现在的东西

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


    } 
} 

我试图纳入一个布尔值,但我不能确定如何比较变量来检查它是哪一种格式。

谢谢堆提前!

+2

http://www.dotnetperls.com/int-parse – Deftwun

+2

有一个*很多*与此代码的问题,因此很难准确地确定你问哪一个。你能否把这个缩小到一个小片段来展示你确切的问题? – Blorgbeard

+0

'int.Parse(age);'不会做任何事情。将结果保存在'int'中。 'int iage = int.Parse(age);' –

回答

0

使用尝试捕捉

string age = console.readline(); 
bool validage = false; 
While(!validage) 
{ 
    try 
    { 
     int myage = int.parse(age); 
     validage = true; 
    } 
    catch 
    { 
     console.write("Please Enter an Integer value for age:"); 
     age = console.readline(); 
    } 
} 
+3

更好地使用tryparse来为您处理错误处理。 – Steve

+0

是的,可以工作,但是我想能够通知用户并提示输入新的信息,tryparse也可以工作,如果你只是想抛出一个错误,继续前进。 – Nikerym

+0

你可以从tryparse中检查一个虚假的回报,然后用它做一些事情,比如Ben的回答。 – Steve

5

相反的Parse,使用TryParse

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

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

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