Monday, September 29, 2014

#LetsPractice C# Interactive calculator.




THE SITUATION:
Today I want to look at another exercise that I found compelling and challenging. This time I was asked to:

  • Create Four Functions that perform various Math operations (* / + - % <<).
  • Do not write Console code in your functions.
  • Call these methods from Main and display the result.
Basically we will create a calculator that can do four things. 

THE PLAN:
To make this console application "interactive". 
In order to keep things organized we should utilize 3 classes: 
The main class: it will hold very little data, just 2 method calls. 
The math operations class: it will store all the math operations we create.
The prompt class: it will prompt the user for input and and perform most everything, by far our largest class. 
Rough implementation:
Start by creating all classes we will need. (Project/addClass/C#class).
Work on the math operations first. Build a function for each: addition, subtraction, multiplication and division. 
Work on the prompt class.

THE SOLUTION STEP BY STEP:
MathOperations.cs: Start with any of the four operations, for example addition. A few things we know are that we need the function to return a number and that it should take at least two parameters.
I decided to use static public so the functions belong to type itself and it can be accessed by other classes. Declare the type of data it returns: double. Why? Because we anticipate what the user may want to do with the function, for example add 2.025 + 10.75. Give the function a descriptive name: Addition. Declare what type of parameters it can take: (double value1, double value2). Open and close {}. The brackets hold the body of the function.
Because we declared value1 and value2 as parameters we don't need to declare them again in the body of the function. Because we are adding two values but only care about the result we need to declare a total variable. You guess it, its of type double. Smooth sailing from here, total will equal value1 + value2 and the only thing left is to declare is what the function has to return (its total). 
This is what addition can look like:
---


---
Try to replicate the results with the other functions(multiplication, division, subtraction).

Prompt.cs: Things get interesting here. First we need to prompt the user to input two different numbers because all our math operations take two double numbers as parameters. To do this we define a function that is not only static but also returns a double and takes in no parameters. The functions does not need to be public since we will only access it with in this class.
Inside the body of this function we define a variable that will be returned by the function when its done executing. In this case I named my variable numberOne and its of type double. Then we prompt the user to input data. Because this is a console application we use the class Console and the method .WriteLine(). Inside .WriteLine we type what ever we want to communicate the user. In this case ("\n Input first number: \n"); We need to catch what ever the user inputs that can be done with the method .ReadLine(). The issue is that an user could input a letter and the program would crash. if is needed to check for that. We can craft a line (and we did) that looks like this if(!double [! in front of double means "not"] .TryParse(Console.ReadLine()), out numberOne)); If the computer can not parse the user input into a readable double it will execute the code inside the {} of the if. That means that we can not only communicate to the user that he or she has made a mistake but we can also re-assign the value of the variable we output(numberOne) to equal the function that the variable is encapsulated inside(promptNumberOne). Effectively restarting the prompting process. This way we allow the user to try again and input the right kind of information. Finally we have to return something, in this case the variable we created at the beginning numberOne.
Here is what the first function in Prompt.cs can look like:
---


---
Try to replicate the results with the function that will capture the second number.

We need to prompt the user for some text as well. This entire program will ask he who uses it to choose what to do. Based on the answer the program will then perform accordingly. Because promtText() its self contained and doesn't need to return data that other functions can use, we declare it as void besides static and public. (This one will need to be public because we will access it from main).

A string holding what the user inputs its imperative. Could be named, answer. Ask the user for input by printing something to the screen.

We said that the calculator could only do four things. That is why it is very simple to implement a system that wold compare user input to four distinct keywords. If the user fails to write this keywords the computer can simply output "I do not understand what you wrote" making it look like the computer is communicating with the user. However before we do that we need to think what will happen when the user fails to utilize our keywords (add, multiply, subtract and divide). We would like to have the program prompt the user to type the right information instead of simply exiting. That is why we need a while loop. To use a the loop we define a random var (variable) to equal true. While this condition is met the computer will always execute what is inside the loop. Inside the loop we have our if statement ready to check the user input against our four keywords. After we check for each possible keyword we would write an else statement that would ask the user to input new data, store it and give retry a value of = true so the loop would run again.

The if statement has what goes inside the ( ) and then what goes inside the { } it does not take ; after the ( ). That would create a syntax error. The computer checks that the user input matches what ever we declared inside the ( ) of the if statement. When a condition is met what ever is written inside the { } will execute.

In this case we declared two double values and then made them equal to another function we created previously "promptNumberOne()" because that funtion its inside the same class and its of type static I do not need to state what class it belongs to, like we have to do when we call Console. Then we can reuse the variable value to now become a new thing instead of having another variable occupying space in memory. Since execution is linear the IDE (integrated development environment) will use value's first value to calculate value's new value (Intentionally convoluted). Then all we do is let the user know what the result of such number combination will be.

There is one more thing can add to make this program a little more interactive and that is the goAgain() function. What this does is ask the user if he or she would like to execute another operation. If the user says no the program exits, if the user says yes the program repeats itself (because retry is still true). The trick to goAgain() lays on its simple execution of another if statement. It is very similar to everything else done so far, but this time what happens  is that this function returns a string that will override the original answer inside the promptText() function. Then the new answer will be compared against our keywords and the program will run again. The only way the output from goAgain() can override the original answer variable is by declaring it again inside the if body of each individual math operation inside the promtText() function. If we give the answer a new variable name then the computer will undergo a logical error and display erroneous data.
Here is what the third function in Prompt.cs can look like:
---

---
Try to replicate the results of the if "add" condition with the other conditions we need to check user input against.

Finally we only have to call this one function from inside the main class. Nothing could be easier and it will look very clean.
Remember that we made the function static so that they belong to type self and do not need to be instantiated. That is a little something I experimented with and so far I am very fond of it. I may find in the future that its not proper to do so, but right now it fits my coding style.

To call the function we simply write insde the { } of the Main function under the class MainModule the following code.
---

---

That is all.

See what the full code and expected output looks like:


THE CODE:
---

---
THE OUTCOME:







The end.
Share This

No comments:

Post a Comment

Contact Me

Do you need to get in touch with me? Shoot me an email!



Made with ♥ in Milwaukee Inspired By Blogger Templates