简体   繁体   中英

How to check if user input is not a number and then display a message in C#?

So this is day 2 of me learning on my own, I'm sure this is a very beginner question here but looking up things I have found using typeof or tryparse but I can't seem to figure out how to use them. I probably shouldn't be trying this at this stage of learning but I figured I'd ask anyway because I really want to know how to do it. I'm following a tutorial but it doesn't cover if the user input is not a number. This is my basic calculator:

using System;

namespace Tutorials
{
    class Program
    {
        static void Main(string[] args)
        {
            string opError = "Invalid Operator";
            string numError = "Enter a valid number";

            Console.Write("Enter a number: ");
            double num1 = Convert.ToDouble(Console.ReadLine());

            Console.Write("Enter Operator: ");
            string op = Console.ReadLine();

            Console.Write("Enter a number: ");
            double num2 = Convert.ToDouble(Console.ReadLine());


            if (op == "+")
            {
                Console.WriteLine(num1 + num2);
            }
            else if (op == "-")
            {
                Console.WriteLine(num1 - num2);
            }
            else if (op == "/")
            {
                Console.WriteLine(num1 / num2);
            }

            else if (op == "*")
            {
                Console.WriteLine(num1 * num2);
            }
            else
            {
                Console.WriteLine(opError);
            }

            Console.ReadLine();
        }


    }
}

I want to be able to check if a user input for num1 and num2 is a number, and if it isn't I want it to display a message which I have set for numError. Now the if and else statements make sense to me because I know the operators being used. When it comes to the user input, that could be anything. That's where I'm confused about how to go about doing this. I read about typeof and tryparse but I don't quite get how to use that in this code. I tried it with tryparse but once I enter a number, it doesn't do anything so I'm assuming I need an if statement in that which I'm still way too at the beginning to know how to do that. What would be the best way to do this with my code? I see there are better ways to do this calculator, I've seen some examples but I'm trying to understand it with the way I have it at the moment.

One solution would be to use double.TryParse , it returns wether the input was a valid number and can be used inside of a do...while loop like so:

double num1 = 0;
do {
    Console.WriteLine("Enter a number:");
} while(!double.TryParse(Console.ReadLine(), out num1));

Which tells the computer to keep prompting the user for input until the parse is successful, ie you got a valid number.

One of the problems with this method is that it doesn't tell the user what went wrong, only to keep entering numbers. But it's relatively simple and you will always get a number at the end.


Another way to use double.TryParse and a loop would be:

double num1 = 0;
while (true) {
    Console.WriteLine("Enter a number:");
    if (double.TryParse(Console.ReadLine(), out num1) {
        // if the parse was successful, we can break out of the loop
        break;
    } else {
        // if the parse was unsuccessful, display an error message and try again
        Console.WriteLine("Invalid number. Try again.");
    }
}

This version is more complicated but it tells the user what went wrong, IMO it's more readable, and it also will always get a number at the end.

Edit: added the second version - thanks @Tomek

Do not use Convert.ToDouble() which is used to convert between numeric types, but rather you should use double.TryParse() which parses a string into a number, like "1.234" to 1.234 .

See an example below

class Program
{
    static void Main(string[] args)
    {
        var input = Console.ReadLine();
        if (double.TryParse(input, out double value))
        {
            // use 'value'
        }
        else
        {
            Console.WriteLine("Please enter a valid number.");
        }
    }
}

Just use this instead:

string c = Console.ReadLine();
int value;
if (int.TryParse(c, out value)) 
{ /* some code here */ }

As you have already found out, there are many ways to solve this problem. However, I would not recommend you to use methods like TryParse() if you don't feel ready for it yet.

Because you set your focus on if-else-statement, i thought the best solution for you could be to handle the input with try- and catch-statements, since it is pretty similiar to an if-else-statement.

So you probably know that if you try to convert a string into a numeric data type (like int or double), you will get an error.

int number = Convert.ToInt32("some text"); //this will cause an error

But actually that's a perfect way to find out if the entered value is a number or not. Now with the try-catch-statement you can detect if an instruction would cause an error without the program crashing.

try 
{ 
   //some code
}
catch 
{
   //this code will be executed when the code above would result in an error
}

Maybe you see some similiarities to an if-else-statement. Like, if the code in the try-block causes an error, the catch-block will be executed, else the try-block itself.

So you could try to convert the user input to a number. If the input was a string, you can output an error message using the catch-statement:

string input = Console.Readline();
double number = 0;
double defaultValue = 1;

try
{
   number = Convert.ToDouble(input);
}
catch
{
   Console.WriteLine(numError);
   number = defaultValue;
}

For example, instead of using a default value, you could also loop the input until the user enters a valid number or just end the program, but I think that's enough for now =)

try and catch are very useful statements, you will still work lot with them in the future!

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