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.
Read More

Sunday, September 21, 2014

#LetsPractice C# Characters Conversion



In this post we will create classes,  instantiate an object to call methods, convert anything into its binary equivalent, and then some. 

If you want the refactor version that I was able to conjure scroll all the way down until you see the refactor picture. 


I will walk you trough the necessary steps to code this application as requested by my class instructor. After that I will explain another method used to solve the same problem with a lot less code (the refactor version)

Lets get started:

What problem are we trying to solve?

We need to create a program that will take user input and then display each letter as:

  1. the actual letter
  2. the decimal value of the key
  3. the hexadecimal value of the key
  4. the octal value of the key
  5. the binary value of the key.

Here is an example of what it will look like:

Char binary   octal   decimal   hexadecimal:
X      xxxxx   xxx     xxxxxx    xx
On top of that we will need to have, in total 3 source files, MainModule.cs,  Info.cs, FormattedOutput.cs.

After we create our C# console application inside Visual Studio we need to create two more classes.
To do that press SHIFT+ALT+C.

First lets take care of the FormattedOutput Class.

FormattedOutput will take care of collecting input, storing it and then transforming that input into the appropriate value.

We know we will create 4 methods inside FormattedOutput:
--


--

The mainMethod() inside of our class is public. Why? Because public is an accessibility modifier. It is not the default modifier, which is private. We specify public to make methods accessible from other classes(such as "convert" a class we will create soon).(Read more about this accessibility modifier here).

If we write mainMethod() as private we will get this error :


Inside mainMethod() we have defined a series of variables that will hold data and utilize other methods, also defined under this class, to prompt the user for some input (the first, second, third and fourth letters of their name). My name has only four letters so I only used four variables.

We have used:
 char letter1, letter2, letter3, letter4; 
Instead of:
char letter1;
char letter2;
char letter3;
char letter4; 
Because we can and its succinct.
So char letter1, tells the computer that an instance of System.char has been initialized(or an object has been created) and defined with name letter1 right now it has no value. 

We will give letter1 a value. 
letter1 = promptForLetter("first");
the value of letter1  is the result of the resolution of promotForLetter() method. promotForLetter() returns char type date while taking in string type(more on that soon). Meaning that letter1 will end up being a char(what it was defined to be). 

Right under letter4... we see displayHeader(); that is another method we have inside the FormattedOutput class that takes in no value and returns no value(void). So it will simply display, in this case, a row of text that identifies what kind of data we are reading when we execute the program. 

Finally we have displayLetter(letter1); this final method returns no value but takes in char type data. 

Lets break down all this methods one by one: 
--

--

promptForLetter()
Is the name of the method.  char is the type of data this method returns. (string ANYNAME) is the type of input that requires. Since we will only call this method from inside this class, we do not need to declare it public. Also methods do not end with ";" instead we use "{ }" and what ever goes inside of those brackets determines what the method can do.

string input;  Why? Like we have done before we need to create an instance of System.String with name input; to hold string type data. At first the computer will tell us that our variable input its assigned but its value never used. That is OK. We will use it in a second.

The same needs to be done with:
char letter;

Now we need to tell the user that we need him/her to input some data so we can modify it. To do that we use:
System.Console.WriteLine()
(remember that because wrote USING SYSTEM at the very top of our code System. its added to pretty much every System-Class-keyword we use and we do not need to write it.)*(note 1 )

Inside WriteLine we have typed an interesting variable, letterNumber, this is that string we said we would feed  char promtForLetter(string letterNumber). Because before, under mainMethod() we wrote down letter1 = pormtForLetter("first"), when we execute the program the computer will go line by line changing the position of the letter the user is superposed to input.

To collect data we use the variable input we have already define and give it a value equal to Console.ReadLine();.
Because this method (promtForLetter()) only returns char we need to convert input from string  to char. That is what we have done with the following line. The interesting part is how  we select how much of input  will be turn into and store in letter. The substring starts at a specified character position and has a specified length. That is why we write(0, 1) meaning start at position 0 and go until position 1. If the user inputs one-hundred letters only the first letter will be turn into a char

return letter; needs to be there so that we are returning something with this method. If we do not write it we will receive this error. 





void displayHeader() its a very short method and will give the illusion that we have created a table.
--

--
We only need to talk the escape sequence we used \t it goes inside the " "  and represents a full Tab.
We will format the way we display letters the same way, that is how we achieve the "table" effect.

void displayLetter(char letter) its our last method under this class. The goal of this method is to take each character the user has input and turn it into its equivalent binary, octo, decimal and hexadecimal notations.
---

---
The method returns nothing but its feed a  char  , that char name can be anything. We choose letter to remember ourselves that promptForLetter returns a char letter and that is what we asked this method to use, under mainMethod().

Why string output;?  we need that variable to be able to format it like we want to. What is .format ? A new method that belongs to namespace System class String.

We use String.Format method with five arguments. The first argument is the formatting string. It specifies how the next four arguments will be formatted. One thing we do not do is use "+" instead we use "," after each argument. So it basically says Argument in position {0} (after the first ",") its going to be letter and after that I want to implement a full Tab. Argument in position {1} needs to be Convert.ToString(letter,2)  and after that implement a full Tab.

What is Convert.ToString(letter,2) this is method converts the value of a char to its equivalent string representation in a specified base. 2 = binary, 8 = octal, 10 =decimal, 16 =hexadecimal.

We utilize Console.WriteLine(output); to have the above string displayed.

That is the end of how to code the class FormatterOutput.cs we will now take a quick look at the other two classes.

-----

Info.cs has one method that needs to be public and does not return anything.
---

---
The only magical thing here is the way we formatted the date:
+ DateTime.Today.ToShortDateString()
All that does is tell the computer, fetch today's date and display it in a succinct manner.  The date will be the same as whatever date you see in your computer.

That is the end of Info.cs


-----

Convertor.cs as I graciously decided to name this program and class, will simply create objects (instances of the other classes) and those objects will call methods from their parent classes (the ones we made public!)
---

---
So like we said, the class name its Convertor, and its only method its Main(). Main() returns nothing and can not be called from within other classes because its private (default mode) and its also static (modifier to declare a static member, which belongs to the type itself rather than to a specific object.)

Then we create an object of class Info named myInfo that its equal to new Info(). 
In C#, the new keyword can be used as an operator, a modifier, or a constraint.
new as an Operator: Used to create objects and invoke constructors. Read more here.

Since we have this new object(myInfo) we can now have it call or point to, a method inside its parent class. In this example that method is .displayInfo(); .

We do the exact same thing for FormatterOuput (create new object from that class and call a method with that object from that class)

Finally we have the Console.ReadLine() so the program won't exit as soon as its ready converting the numbers. 


-----


We are done! but there is more! I will now refactor this code with a much simpler way of doing things(not the way we were supposed to do it, but still a very cool way I think). First the flowchart that helped me along:


We could do all of this in one class, but part of the objective of this chapter of the book was to learn about creating objects and calling methods. We can create a new project and add one extra class to it. FormattedOutput.cs under its mainMethod() we can write the following code:
---


---
char[] characters; Is a char array.A char array stores string data, character by character. It is an alternative to using StringBuilder for creating string data quickly.

We then prompt the user to write what ever he wants, that's right no more counting how many letters an user can type. The user could write until his fingers get tired and then some.

Take characters and convert what the user writes (we capture that with Console.ReadLine()) .ToCharArray(); We need to do that because what the user input will always be initially formatted as a string and we can not implicitly change a string into a char. We have to explicitly tell the computer we want to do it.

Now it gets fun, a simple header can be implemented by just asking the machine to type it out once using:
Console.WriteLine("Char\tBinary\tOctal\tDecimal\tHex");
And then foreach comes into play. Because our data its stored inside an array(our simple container for individual char  values right now.) we can use foreach  to modify what happens to every item inside that array. foreach (var X in characters(the name of our array) do Y. 

Our main class remains the same, it will create the same objects and call the same methods.

That is all. I salute thee for sticking to the end. I will only post the entire code, with out breaks, upon request just because this is a lengthy post.


Notes:

(1) System would be the namespace, Console would be a class under that namespace and WriteLine is a method of Console.



The end. 
Read More

Saturday, September 20, 2014

How to create a C# console application.



Lets get to it:

Open Visual Studio Express 2013 for Windows Desktop:


You will be greeted by a similar screen:



Click File then New Project:


Be sure to select Visual C# under "Templates":


Under "Visual C#" choose "Windows" and right next to that select "Console Application":

Give the file a meaningful name:








Happy coding:


The end.












Read More

Saturday, September 13, 2014

#Letspractice C# CarpetCalculator




Lets talk practice. I am going to break down a simple coding exercise that I found in a tome of forgotten lore(It is most definitely not “C# programming from problem analysis to Program Design(fourth edition)”).

I will try to cover as much ground as possible. Basically almost everything presented in the second chapter and then some. I will borrow some knowledge from Shawn Sommer, he wrote a great post called everything-isnt-int. We will use the theory he exposed to make our program as light as possible.

So basically we are designing an application to determine what it would cost to put new carpeting in a single room. Single room size:

Length = 12 feet 2 inches.
Width = 14 feet 7 inches.

We can choose from two carpet options. They are:

Berber(best) @ $27.95 per square yard.
Pile(economy) @ $15.95 per square yard.

The question is, what will each selection cost? Before we code we need to analyze the data, and plan our approach. What do we know: We are given feet and inches(whole numbers and integers) to work with but the price(number with decimal part, or “double” or “float”) of the carpet comes per square yards.

To determine square yards we first must calculate square feet. To do that we first convert all our feet and inches to feet. The book tells us that we can use int for all the values but we know better because we have read everything-isnt-int. Right? SO we scrap that and we do it our way.


For now lets focus on what values are constant. We know that there are 9 square feet in a square yard, it's because 1 yard is 3 feet and in a square all sides are equal in length, which makes 1 sq. yard equals to 3 * 3 = 9 square feet.(This data came from here).
So that will be a constant, we can give it a nice descriptive identifier and we are done: (Remember the book says this are integers but we know that we don’t need any more than a byte to identify this constant)


Now we do the same for:


We also know that the best and worst carpet have immutable names (for this example) so we can call them constants as well:

Now it would be a good time to think about and craft a flowchart. The more planning we do the least debugging we will have to deal with later. Here is a picture of my flowchart: It is the same one as in the book but this one I made myself using gliffy.



CarpetCalculator is only going to be 1 class that executes right then and there so we could also do a class diagram but we do not absolutely need it and this post is long enough as is. Alright now we are ready to start the coding. Refer to this post if you have never ever created a C# Console Application on Visual Studio before. We start by: ---
--- Because this program has only one class “CarpetCalculator” evertyhing will happen inside this Main() the second step is to define our constants or “const” ---
--- So far so good, notice how we did not write ---
--- because 12 fits just fine into a byte and we know it won’t change. Lets continue. Now we look at our flow chart to get an idea of what other variables we need to define. ---
--- Same as before, ushort instead of byte. I did this just to show another type of numeric value we can use to define our variables. I am sure you know we could've used byte. Now we define all our floats. We use floats instead of the default doubles because floats are 32 bits in size instead of 64, and they are precise up to 7 digits which is more than enough for this exercise. ---
--- It is time to basically follow the flowchart step by step now: ---
-- Mind about how we cast the roomLengthInches & roomWidthInches with a prefix that looks like this (float). And also pay close attention to the suffix we used on carpetPrice. We do this because the default floating point type is double & we must let the computer know 27.95 is not a double but a float. If we don’t we will get a syntax error. Now to finish up the code add this part: ---
--- Here we are formatting a string for the first time: ---
--- Because we are going to end up with a number with several decimals and we only care about how many cents that would be we need the decimals at only two digits. To do this we use “{0:c}”, totalCost totalCost will come up looking like dollars and cents, making a lot more sense to the user. n\n\ are escape operators for making sure the info is not display right on top of the previous data. And now we are finally done. If we run the program we should see this:

       Total Cost of Berber is $551.02
       
       Total Cost of Pile is $314.45  

And that basically does it. Our code looks professional and it is very light! Here is all the code at once:

--If you have any questions leave a comment in the section below I will get to it as soon as posible. Cheers


Read More

Contact Me

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



Made with ♥ in Milwaukee Inspired By Blogger Templates