user3554677
user3554677

Reputation: 35

C# Parse string integer error?

I've literally just started C#... Today and I'm attempting to write a very simple application. However, when I use the console.readkey if anything other than a number is entered, it immediately crashes.

I completely understand that its attempting to parse out the numbers and convert them to a string however though, How do I keep the application from crashing or failing if someone doesn't insert a number. I've googled around but apparently this is a pretty specific thing.

All I'm trying to do is nullify or Parse out anything that's not numbers so the application doesn't get confused and shut down.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
        Console.Write("what is your age?");
        string agestring = Console.ReadLine();
        int age = Int32.Parse(agestring);

        if (age >= 21)
        {
            Console.WriteLine("congrats, you're you can get drunk!");

        }
        else if (age < 21)
        {
            Console.WriteLine("Sorrrrrryyyyyyy =(");
        }
        else
        {
            Console.WriteLine("Sorry Thats not a valid input");
        }
    }
}

Upvotes: 0

Views: 438

Answers (2)

Christos
Christos

Reputation: 53958

Try this one:

int age;

if(Int32.TryParse(agestring, out age))
{
    if (age >= 21)
    {
        Console.WriteLine("congrats, you're you can get drunk!");
    }
    else
    {
        Console.WriteLine("Sorrrrrryyyyyyy =(");
    }   
}
else
{
    Console.WriteLine("Sorry Thats not a valid input");
}

Using the Int32.TryParse method you can check, if the parsing of the input is successful. If it is not, then you print a message to the console.

Upvotes: 3

Parimal Raj
Parimal Raj

Reputation: 20575

You can use the Int32.TryParse method

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
        Console.Write("what is your age?");
        string agestring = Console.ReadLine();
        int age;

        if (Int32.TryParse(agestring, out age))
        {
            if (age >= 21)
            {
                Console.WriteLine("congrats, you're you can get drunk!");

            }
            else if (age < 21)
            {
                Console.WriteLine("Sorrrrrryyyyyyy =(");
            }


        }
        else
        {
            Console.WriteLine("Sorry Thats not a valid input");
        }


    }
}

}

Upvotes: 0

Related Questions