Number User Input


Now, the fact that you can log string user input, process it, and then give an answer to it is great. But it’s not enough, because what happens when you don’t have code to deal with a certain string they may type in incorrectly? It will give an error or something completely different that you may not have intended. That is why numeric user input is at best. In this sub-section we’ll be exploring user input using the program we made in the last sub-section. We’ll just add one thing on to make it even better. We’ll start with going back to our code and creating a new variable, it will be an int, and we will call it “intAge”.



Next I’ll get you to make the question, which will be ‘Console.WriteLine(“What is you age?”)’.



Now, this particular line of code will determine whether you imputed a numeric value and it will use that value. If you type something like a string, it will give you a null answer and will prevent you from continuing. Type this ‘while (!(Int32.TryParse(Console.ReadLine(), out intAge))) / {Console.WriteLine("I'm sorry, age must be an integer.\nTry again.");}’.



Once you’ve done that we just need to tweak our concatenation a little.



If you start up your new and improved program, you’ll see some differences you didn’t see before. There will be an extra question and some of the words and sentence have changed. Now, if you typed in a string when the program asked for an int (if the program asked for your age and you gave your name) it would activate the else statement where it would loop and tell you to try again.



Next, we’ll start looking at different ways you can calculate integer calculations in C#.