简体   繁体   中英

Checking user input in C#

I just wrote my first C# console application, I am still a beginner. Anyway, I tried the code below and it seems to work, its for solving quadratic equations. I'd like to add code for a situation whereby a user inputs a string instead of an integer and give an error message any ideas as to how to implement this?

namespace Quadratic_equation
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("welcome to seyi's quadratic calculator!!!");
            Console.Write("a:");
            double a = Convert.ToInt32(Console.ReadLine());


            Console.Write("b:");
            double b = Convert.ToInt32(Console.ReadLine());
            Console.Write("c:");
            double c = Convert.ToInt32(Console.ReadLine());
            if ((b * b - 4 * a * c) < 0) {
                Console.WriteLine("There are no real roots!");
            }
            else {
                double x1 = (-b + Math.Sqrt((b*b)-4*a*c)) /2*a;
                double x2 = (-b + Math.Sqrt((b*b)-4*a*c)) /2*a;
                Console.WriteLine("x:{0}",x1);
                Console.WriteLine("y:{0}",x2);
            }

            Console.ReadKey();
        }
    }
}

You can use Int32.TryParse method to check your string is a valid integer or not. This method returns a boolean value for your conversation is succeed or not.

Converts the string representation of a number to its 32-bit signed integer equivalent. A return value indicates whether the conversion succeeded.

And I don't understand why you want to keep as double the return value of Convert.ToInt32 method. These factors (a, b, c) should be integer, not double.

int a;
string s = Console.ReadLine();
if(Int32.TryParse(s, out a))
{
   // Your input string is a valid integer.
}
else
{
  // Your input string is not a valid integer.
}

This Int32.TryParse(string, out int) overload uses NumberStyle.Integer as default. That means your string can have one of these;

  • Trailing white spaces
  • Leading white spaces
  • Leading sign character

Check out int.TryParse

   int number;
  bool result = Int32.TryParse(value, out number);
  if (result)
  {
     Console.WriteLine("Converted '{0}' to {1}.", value, number);         
  }
  else
  {
     if (value == null) value = ""; 
     Console.WriteLine("Attempted conversion of '{0}' failed.", value);
  }

Use a try-catch block in a do-while loop:

bool goToNextNum = false;
do
{
    try
    {
        double a = Convert.ToInt32(Console.ReadLine());
        goToNextNum = true;
    }
    catch
    {
        Console.WriteLine("Invalid Number");
    }
} while (goToNextNum == false);

This will loop until a is a valid number.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM