简体   繁体   中英

C# - How do I create an exception if the User enters a text when expecting a number?

Here is the code I had written for a Calculator without any tutorial, and I want to keep it that way, so I want to imagine and create my own code since i'm just a beginner.

Console.Title = "My Epic Calculator !";

            var numOne = "";
            var numTwo = "";
            var term = "";
            var answer = 0;
            
                    Console.WriteLine("Hello there, welcome to my calculator !\nIt can calculate everything. Come on, try it !");

                    Console.WriteLine("Enter your first number below.");
                        numOne = Console.ReadLine();
                        if (numOne == "")
                        {
                            Console.WriteLine("Please enter a valud number");
                        }

                        int firstTerm = int.Parse(numOne);

                    Console.WriteLine("Now enter your second number.");
                        numTwo = Console.ReadLine();
                        int secondTerm = int.Parse(numTwo);

                    Console.WriteLine("Choose your mathematical option: x, /, + and -");
                        term = Console.ReadLine();

                        if (term == "x")
                        {
                            answer = firstTerm * secondTerm;
                        }

                            else if (term == "/")
                            {
                                answer = firstTerm / secondTerm;
                            }

                            else if (term == "+")
                            {
                                answer = firstTerm + secondTerm;
                            }

                            else if (term == "-")
                            {
                                answer = firstTerm - secondTerm;
                            }

                        
                    Console.WriteLine($"And your answer is {answer}, see it's pretty cool huh!");
                    
                    Console.ReadKey();

As you can see, it lacks an exception if the user enters in text where you expect a number to be written in (numOne / numTwo for example). And unfortunately I don't know how to resolve this, can anyone help? Thank you.

I would also appreciate a few tips to optimise my code as I know it is very messy with my tons of If's.

int numOneIntValue= 0; if (!int.TryParse(numOne, out numOneIntValue)) { Console.WriteLine("numOne is not a number!"); } int numTwoIntValue= 0 ; if (!int.TryParse(numTwo , out numTwoIntValue)) { Console.WriteLine("numTwo is not a 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