我创建了一些类,在一个实例中,我希望程序读取答案(数字)。我试图将类设置为字符串和int,但仍然有问题。请耐心等待,我刚开始学习编程。
public **int** Age { get; set; }
Animal cuddle = new Animal();
cuddle.Color = "";
cuddle.Age = 0;
cuddle.Name = "";
cuddle.Type = "";
Console.WriteLine("Hi, {0} How old do you want your {1,2} to be?\n Remember, if your {3} is older then 5 you will have to give her double!!!", name, cuddle.Color, player);
cuddle.Age = **Console.ReadLine**();
if (cuddle.Age < 5)
{
在这种情况下,它不接受Console.ReadLine.
如果我将int更改为string:
public **string** Age { get; set; }
然后它不接受
if (**cuddle.Age < 5**)
我试过没有括号和/或(**cuddle.Age = < 5**)
答案 0 :(得分:2)
int age = 0;
if(int.TryParse(Console.ReadLine(), out age)) //It can be parsed as integer:
{
if(age < 5)
{
// do your work
}
}
当输入不可解析时,您可以更进一步并重复阅读行:
int age = 0;
while(!int.TryParse(Console.ReadLine(), out age));
if(age < 5)
{
// do your work
}
以下是 DEMO
答案 1 :(得分:1)
您可以在用户输入上转换为int:
int theInt = Convert.ToInt32(Console.ReadLine());
这可能与此问题重复:Reading an integer from user input