【问题标题】:how to convert type string to int [duplicate]如何将类型字符串转换为int [重复]
【发布时间】:2017-09-08 11:02:14
【问题描述】:

我创建了一些类,在一个实例中,我希望程序读取答案(数字)。我试图将类设置为 string 和 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 更改为字符串:

 public **string** Age { get; set; } 

那么它不接受

if (**cuddle.Age < 5**)

我试过不带括号和/或(**cuddle.Age = &lt; 5**)

【问题讨论】:

    标签: c#


    【解决方案1】:
    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

    【讨论】:

    • 谢谢阿什坎。它没有显示任何错误,但最终没有工作。当这个问题被回答时,它把我拒之门外。你能帮帮我吗?
    • @Itzik 请来chat讨论
    【解决方案2】:

    您可以根据用户输入强制转换为 int:

    int theInt = Convert.ToInt32(Console.ReadLine());
    

    这可能是这个问题的重复:Reading an integer from user input

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-18
      • 2015-06-02
      • 2015-06-18
      • 2017-05-07
      • 1970-01-01
      • 1970-01-01
      • 2012-12-14
      • 1970-01-01
      相关资源
      最近更新 更多