2

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.

1
  • 1
    also make sure in your division to check for 0 for num2 :-) Commented Jan 15, 2021 at 0:04

4 Answers 4

2

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, i.e. 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

Sign up to request clarification or add additional context in comments.

6 Comments

i know the loop criteria is very compact but the question is do you sacrifice readability and or maintainability? It also seems the author is pretty new to the materia and I guess it would be easier fort he author if the focus would be in better readable code rather keeping it compact. Maybe you can add the other variant as well just for "beginners", what do you think?
@Tomek great idea! I'll start working on it right now.
Thanks, that worked! I tried the second method, I found that easier to understand. In the first one, I don't know what "do" actually does yet. I do have some questions, so I can understand what this did better. I kinda understand TryParse but also not really. Like it will convert the string version of a number and if it can convert it, it passes if not it fails. Why would you want to convert a string to a number? Is this something advanced and I just shouldn't worry about it yet? So in my case typing other than a number would fail the "conversion" but isn't that the purpose of TryParse?
What would a situation look like if it did parse successfully? Also double num1 = 0 why did num1 have to be 0? Could it have been any number? I'm just guessing here, is it because a number was assigned to num1 so (double.TryParse(Console.ReadLine(), out num1)) it tried parsing the input into a double and if it passed then it breaks else it writes the error message. Is that understanding correct? Sorry, still trying to memorize and understand the structure of the syntax.
By "What would a situation look like if it did parse successfully?" I mean as in converting a string to a number. Or am I just completely understanding TryParse incorrectly here?
|
1

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.");
        }
    }
}

Comments

0

Just use this instead:

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

Comments

0

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!

3 Comments

It is generally considered bad practice to use exceptions (try { ... } catch { ... } ) as control flow
Surely it's not the best method. I just remember my first calculator-program that looked like this and i wouldn't feel well by using methods i don't understand so far.
The equivalent TryParse is a very simple API, not complex or difficult to understand in my opinion. See other answers for an example. Using exceptions as control flow in C# is generally an anti pattern that you want to avoid.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.