Creating a Calculator with C# Part 2: Creating Variables, Getting User Input, Doing Math, and Handling Exceptions

Welcome back. Hopefully the last tutorial on C# sparked your interest. If it didn’t, then I commend you for still giving this tutorial a shot. We’re going to learn how to use variables, get input from the console, and then conduct mathematical operations on the input. We’ll even display the result. Yes, we’re building a simple adder.

To begin, either create a new project or (gasp!) delete your Hello World project. I recommend the former; you probably haven’t been able to show it to your grandkids yet. Then, in the main method (just like before), we’re going to declare two variables: number1 and number2. How do you declare variables, though? Like this:

[type] variableName;

What’s [type]? Type is class the variable is. C# is called a strongly-typed language because you can’t mix and match types. If you declare a variable as an integer (using “int” or “System.Int32″ or “Int32″ as the type), you can’t put a string in it. This prevents errors down the line and encourages you to code better. Now, declare those variables!

static void Main(string[] args)
{
    int number1;
    int number2;
    // More code goes here!
}

This also seems like a good time to tell you two more things about C#:

  1. Every code statement you write (like int number1) has to end with a semicolon. Semicolons are so important that you can have a line containing nothing but a series of semicolons and your project will run properly! Try it if you don’t believe me.
  2. The line beginning with // is called a comment. Comments are ignored by the compiler and contain information to make your code easier to read. You don’t need a semicolon after a comment. C# also has what are called block comments. Block comments start with /* and end with */. Everything between the start and end is ignored. No matter how nicely you ask the computer to work in your comments, they will be ignored.

So, we’ve got our variables. We’ve got more knowledge about the C# syntax. Let’s fill those variables with numbers. Remember Console.WriteLine() and Console.ReadLine()? We’re going to use them again. We’re also going to use another method called int.Parse() which takes a string as an argument. Recall that I told you C# is strongly typed. The Console.ReadLine() method returns a string value, even if the user types in numbers. The int.Parse() method converts the numbers a user types in to a real integer. Here we go.

static void Main(string[] args)
{
    int number1;
    int number2;
 
    Console.WriteLine("Enter a number, then hit enter:");
    number1 = int.Parse(Console.ReadLine());
 
    ; ; ; ; ; ; ; ; ; ; ; ; ;
}

Just for fun, I threw in a line of semicolons; semicolons are awesome anyway. We’ve seen Console.WriteLine() before, but look at the line below that. Console.ReadLine() returns a string, and we’ve used it as the string argument for int.Parse. The value the user enters will be passed to int.Parse, and then the integer version is stored in number1. Now let’s take care of the other number.

static void Main(string[] args)
{
    int number1;
    int number2;
 
    Console.WriteLine("Enter a number, then hit enter:");
    number1 = int.Parse(Console.ReadLine());
    Console.WriteLine("Enter another number, then hit enter:");
    number2 = int.Parse(Console.ReadLine());
}

The two lines we’ve added are identical to the two we added before. Next, let’s do something with our new-found numbers. We’re going to add them together and write them to the console. Let’s create a new variable called sum and assign it to the sum of number1 and number2. C# spoils you because it follows order of operations, unlike other languages I post about like PBASIC. The addition operator in C# is +, and using it is rather intuitive:

static void Main(string[] args)
{
    int number1;
    int number2;
 
    Console.WriteLine("Enter a number, then hit enter:");
    number1 = int.Parse(Console.ReadLine());
    Console.WriteLine("Enter another number, then hit enter:");
    number2 = int.Parse(Console.ReadLine());
 
    int sum = number1 + number2;
}

We’ve created another variable called sum and immediately assigned it to the sum of number1 and number2. Sum is an int (32-bit integer – .NET has loads of other numbers like 8, 16 and 64-bit integers, decimals, and single and double-precision floating points), so we make sum an int as well. If you wanted to use multiplication (*), subtraction (-), division (/), or any other operation, you would substitute the corresponding operator in for the plus sign. Now, The last thing we have to do is print the sum to the console and wait for the user to exit.

static void Main(string[] args)
{
    int number1;
    int number2;
 
    Console.WriteLine("Enter a number, then hit enter:");
    number1 = int.Parse(Console.ReadLine());
    Console.WriteLine("Enter another number, then hit enter:");
    number2 = int.Parse(Console.ReadLine());
 
    int sum = number1 + number2;
    Console.WriteLine("The sum is: " + sum.ToString());
    Console.ReadLine();
}

What on earth is this ToString() thing? And why is there a plus sign on the string!? I thought C# was strongly typed, and the + goes with numbers!! Whoa there. I’m glad you’re thinking about this typing thing; it will save you a lot of headaches later on. We’ll start with the plus sign. + has another purpose besides addition: concatenation. Concatenation is the process of appending one string on the end of another. If you were to concatenate “hello” and “world” by writing “hello” + “world”, the result would be “helloworld”.

The ToString() thing should make a little more sense. Remember that sum is an integer, not a string. Calling ToString() lets us use it as a string. Every single class you can declare as a variable in the .NET framework has a ToString() method. Even System.Object, the basis for every other class in .NET (if you want to understand this better, look up inheritance. It’s sort of an advanced topic but there’s nothing wrong with being exposed to advanced topics!) has a ToString() method. Return values vary; ToString() tends to work well with numbers and poorly with more complicated classes like System.Windows.Forms.Form. Anyway, back on track – once sum is usable as a string, we append it to the end of the other string. Go ahead and run your code by hitting F5.

Adder Program Console Image

Yay! It works!

We only have one topic left to cover in this lesson: handling exceptions. What’s an exception? Exceptions are how your program handles errors. Errors happen all the time. Even the almighty Google has to handle errors.

Google Exception Image

I wonder why that page can’t be found?

In this case, Google’s server code searched for whatever file would normally be served for google.com/the long file name that doesn’t exist, and didn’t find it. In .NET, a FileNotFoundException would result. When an exception occurs, it has been “thrown”. If an exception is thrown and not caught, it will cause your program to come crashing down, just like a baseball that isn’t caught. You might be thinking that this program is way too simple to have to worry about exceptions, but every application that handles user input should have very careful exception handling because to write bulletproof code, you have to assume your users are less technically competent than you are. You have to assume they don’t know what they’re doing and will send you angry emails about how your application is full of bugs. Let’s pretend to be a dumb user right now. Run your application again (close it then hit F5 in Visual C#), and type in some gibberish instead of a number.

Exception in Visual C# image

You don’t have to send yourself any angry emails.

Congratulations, you’ve just seen your first exception. If you haven’t followed the code here exactly, it may not be your first. The question is, how do you keep your program from crashing when a user puts random input is? You can encapsulate your code in a try, catch block. A try, catch block lets you run code and have code that is run in the event of an exception (but not otherwise). We’ll print the exception message to the screen and then try again with our try, catch block. Modify your code to look like this:

static void Main(string[] args)
{
    try
    {
        int number1;
        int number2;
 
        Console.WriteLine("Enter a number, then hit enter:");
        number1 = int.Parse(Console.ReadLine());
        Console.WriteLine("Enter another number, then hit enter:");
        number2 = int.Parse(Console.ReadLine());
 
        int sum = number1 + number2;
        Console.WriteLine("The sum is: " + sum.ToString());
 
        Console.ReadLine();
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
        Main(args);
    }
}

Just like a method, a try, catch block uses curly brackets ( { and } ) to signify where the associated code goes. One of the wonderful things about C# is how the curly brackets let you format your code the exact way you want it, as opposed to Python which forces you to adhere to its own indentation requirements. Anyway, The code in the try block remains unchanged and if there are no errors, users will not know the difference from before. If, however, there is an exception, the user will see the message (which is a property of System.Exception – more on this in another lesson) and then get another shot at entering numbers, because the method Main calls itself, which causes the program to start over.

Image of exception handling

That’s way better than crashing.

Be careful when you instruct a method to call itself. If there is no way to exit the method (in this case, if the user successfully adds two numbers then hits enter), you will end up in an infinite loop. That’s fine in a simple application like this, but more complicated applications could crash.

I know you have one last question – why are we catching an Exception when Visual C# clearly told us that we were dealing with a FormatException? C# is strongly typed so we should have to catch what we throw? This is like catching a soccer ball with a baseball glove, right? Not exactly. It’s closer to catching a baseball with yellow stitches with a baseball glove.

FormatExceptions (and every other exception you will ever handle) are Exceptions because of something called inheritance (remember, I put a link at the top of this post). If you catch Exception ex, then you are catching every conceivable exception that could ever be thrown in that block of code. So, if you bother to watch for exceptions, why not take care of all of them?

That’s it for this installment. If you want to go a little farther, change this application to multiply three numbers together. Thanks for reading!

One thought on “Creating a Calculator with C# Part 2: Creating Variables, Getting User Input, Doing Math, and Handling Exceptions”

Leave a Reply

Your email address will not be published. Required fields are marked *


+ 4 = ten

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>