Try Parsing

Line: Conditional Line
Hard Difficulty Selection Learning Outcome One Exercise
Type: Walkthrough
You should have completed: Math Functions This topic leads to: Happiness Meter

Summary

So far, if the user has entered a string or a number with a decimal point for an input where we asked for an integer, our programs have crashed. Proper exception handling will be introduced later in the module, but there is a set of functions provided to us that can make user input more robust.

Note that .Net has its own names for the variable types we use, so int is Int32, float is Single and so on. There is more information about this mapping on the C# reference site.

Task

  1. Create a new console application
  2. Within "main" type in code to ask the user for a whole number for their age.
  3. Instead of using Int32.Parse to convert the user's input, use the TryParse function instead.

    Note that this method returns a Boolean value telling us if it was successful or not. We also need the out keyword to allow the method to alter the value in the variable we pass in. Normally a value type variable passed to a method is copied and thus the original value remains unchanged.

  4. Now finish the program to either tell the user how old they are or to tell them that their input was not in the right form
  5. Test the program with different inputs, including 20, 17.5 and 'hello'

Questions

  1. How would you alter this code to instead accept ages like 21.5 years