0

so my problem is that when the user enters an letter it kind of crashes my console app haha now i want to put a validation in my code that will ask them to re-enter every time they enter a letter that is not a number but am having trouble doing so :( i have other methods that i would like to implement the answer on to as well, thank you guys.

   {

        double r;
        Console.WriteLine("Please enter the radius: ");
        r = Convert.ToDouble(Console.ReadLine());
        double areaCircle = pi * (r * r);
        Console.WriteLine("Radius: {0}, Area: {1}", r, areaCircle);
        Console.ReadLine();

    }
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • 1
    Possible duplicate of [How can I validate console input as integers?](http://stackoverflow.com/questions/4804968/how-can-i-validate-console-input-as-integers) – techspider May 10 '16 at 15:54
  • 2
    Have a look at `Int32.TryParse`. – Danny Goodall May 10 '16 at 15:55
  • 3
    And possible duplicate as well of [How do I only allow number input into my C# Console Application?](http://stackoverflow.com/questions/13106493/how-do-i-only-allow-number-input-into-my-c-sharp-console-application) – Dick Bos May 10 '16 at 15:55

3 Answers3

2
double userInput;
while(!double.TryParse(Console.ReadLine(), out userInput))
{
    Console.WriteLine("Your input was not numeric. Please enter a number.");
}

When the while loop has exited, userInput will contain a double parsed from Console.ReadLine().

If you're doing this more than once then I'd write a function. You probably also need a positive number.

double GetInput(string prompt)
{
    Console.WriteLine(prompt);
    double userInput;
    while(!(double.TryParse(Console.ReadLine(), out userInput) && userInput > 0))
    {
        Console.WriteLine("Please enter a positive number.");
    }
    return userInput;
}

Then

var r = GetInput("Please enter the radius:");
Scott Hannen
  • 27,588
  • 3
  • 45
  • 62
0

Use TryParse

{

   double r;
   Console.WriteLine("Please enter the radius: ");
   Double.TryParse(Console.ReadLine(), out r);
   double areaCircle = pi * (r * r);
   Console.WriteLine("Radius: {0}, Area: {1}", r, areaCircle);
   Console.ReadLine();

 }
Mostafiz
  • 7,243
  • 3
  • 28
  • 42
0

Instead of using Convert.ToDouble, use TryParse instead:

    double r;
    string line;
    Console.WriteLine("Please enter the radius: ");
    line = Console.ReadLine();
    if (double.TryParse(line, out r))
    {
        double areaCircle = pi * (r * r);
        Console.WriteLine("Radius: {0}, Area: {1}", r, areaCircle);
        Console.ReadLine();
    }

To make this more robust, try using a while loop to ensure you get valid input.

Hrethric
  • 96
  • 7