1

I have created some classes and in one instance, I want the programme to read the answer (numeric). I have tried to set the class as string and as int but continue to have problems. Please bear with me I am just starting to learn programming.

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

In this instance it doesn't accept the Console.ReadLine. If I change the int to string as:

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

then it doesn't accept

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

I have tried without the brackets and/or with (**cuddle.Age = < 5**)

Itzik
  • 45
  • 1
  • 1
  • 7

2 Answers2

2
int age = 0;
if(int.TryParse(Console.ReadLine(), out age)) //It can be parsed as integer:
{
     if(age < 5)
     {
        // do your work
     }
}

You can go further more and repeat reading line while the input is not parse-able:

int age = 0;
while(!int.TryParse(Console.ReadLine(), out age));
if(age < 5)
{
   // do your work
}

Here is the DEMO

Ashkan Mobayen Khiabani
  • 33,575
  • 33
  • 102
  • 171
  • Thanks Ashkan. It didn't show any errors but it didn't work at the end. It shut me out when this question was answered. Can you help me? – Itzik Sep 09 '17 at 21:25
  • @Itzik please come to discuss in [chat](https://chat.stackoverflow.com/rooms/153406/discussion-between-rev4-and-ashkan-mobayen-khiabani) – Ashkan Mobayen Khiabani Sep 09 '17 at 21:29
1

You can cast to an int, on user input:

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

This is possibly a duplicate of this question: Reading an integer from user input

Stuart
  • 6,630
  • 2
  • 24
  • 40