Incorporating a Variable in Output

After the ReadLine() code is placed in memory named userName, containing whatever text the user typed. The next step is to print out this value to the user as a customized greeting.

The line that provides the greeting looks like this:

Console.WriteLine("Hi there, {0}!", userName);

If you compare this line to the output, you can probably figure out what’s going on. The computer says, “Hi there,” places the user’s name in place of the {0} stuff, and adds an exclamation point to the end. The WriteLine() method can be used to combine plain text with variables. It works by first expecting a line of text. If you w ant to add variables in your message, you can replace a variable with a number inside braces. Computers usually start counting at zero, so userName is variable number zero, and the value of userName is printed out to the screen. If you ask for a first name and a last name, the line might look like this:

Console.WriteLine("Hi there, {0} {1}!", firstName, lastName);

If you also incorporate a middle initial, the code might end up like this:

Console.WriteLine("Hi there, {0} {1}. {2}!", firstName, mi, lastName);

As you can see, the plain text you want to write should be added first, with placeholders for any variables you might want to include in the message. Then you provide a list of variables. Of course, the order of the variables in the list can make a big difference, and if you refer to variable number 1, you must have at least two variables in the list.

Computers begin counting at zero! The first element in a list is not number one but number zero. Forgetting this is easy if you’re new to programming! Most of the time in your writeLine() statements, you will simply be referring to variable zero ({0}), or you will have no variables at all. By the way, if you want to know the fancy computer scientist name for placing the variables inside the text, it’s string interpolation. See whether you can work that phrase into your dinner conversation tonight.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.173.199