Object Oriented Programming and C#: Simple Program to add three numbers

The following is a simple program that takes a user input of three numbers and adds them but does not crash when an exception is thrown (eg. if a user inputs a non integer value). The “int?” variable is used to include the “null” value used to signify that a bad input was received. The user is notified instantly when an incorrect input is received by the program with a “Bad input” command prompt message.

c1

The code above shows that the GetNumber() method is called (shown below) three times, and as long as these are integers, they are summed and printed to the console after being converted to a string.

c2

The code shows that as long as the sum of the three integers is not equal to null (anything plus null is equal to null, so if at least one input is a non-integer this will be triggered) the Console will print the sum of the three numbers. The GetNumber() method uses the “TryParse” method to convert each string input to an integer. This will handle exceptions that are triggered by passing a non-integer to the command line. It also gives a convenient return of “null” which is used above.

The following shows the effect of both a summation and an incorrect input summation failure.

correct

incorrect

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s