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