Ben*_*dis 2 c# console console-application c#-4.0
我需要拒绝在我的控制台应用程序中编写字符串的能力,此时,当输入文本而不是数字时,控制台崩溃.
我现在有类似的东西
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();
}
}
Run Code Online (Sandbox Code Playgroud)
我试图合并一个布尔值,但我不确定如何比较变量以检查它的格式.
谢谢你提前!
而不是Parse,使用TryParse.
int age = 0;
if (Int32.TryParse(Console.Readline, out age)
// Correct format.
else
// error!
Run Code Online (Sandbox Code Playgroud)
什么TryParse()都行,就是把用户输入,尝试以解析它为int,如果成功,将输出一个int(和bool = true),否则会输出bool = false.
| 归档时间: |
|
| 查看次数: |
141 次 |
| 最近记录: |