Escolar Documentos
Profissional Documentos
Cultura Documentos
Programmes work by manipulating data stored in memory. These storage areas come under the general heading of Variables. In this section, you'll see how to set up and use variables. You'll see how to set up both text and number variables. y the end of this section, you'll have written a simple calculator programme. !e'll start with something called a String variable. String Variables in C#.NET The first type of variable we'll take a look at is called a String. "tring variables are always text. !e'll write a little programme that takes text from a text box, store the text in a variable, and then display the text in a message box. ut bear in mind that a variable is #ust a storage area for holding things that you'll need later. Think of them like boxes in a room. The boxes are empty until you put something in them. You can also place a sticker on the box, so that you'll know what's in it. $et's look at a programming example. If you've got your pro#ect open from the previous section, click File from the menu bar at the top of %isual &'. (rom the (ile menu, click Close Solution. "tart a new pro#ect by clicking File again, then New Project. (rom the )ew Pro#ect dialogue box, click on !indows *pplication. (or the )ame, type String Variables. &lick +,, and you'll see a new form appear. *dd a button to the form, #ust like you did in the previous section. &lick on the button to select it -it will have the white s.uares around it/, and then look for the Properties !indow in the bottom right of %isual "tudio. "et the following Properties for your new button0 Name0 btn"trings Location0 12, 345 Size0 362, 72 Text0 8et Text ox 9ata Your form should then look like this0
!e can add two more controls to the form, a $abel and a Text ox. !hen the button is clicked, we'll get the text from the text box and display whatever was entered in a message box. * $abel is #ust that0 a means of letting your users know what something is, or what it is for. To add a $abel to the form, move your mouse over to the Toolbox on the left. &lick the Label item under Common Controls0
The $abel has the default text of label3. !hen your label is selected, it will have #ust the one white s.uare in the top left. !hen it is selected, the Properties !indow will have changed. )otice that the properties for a label are very similar to the properties for a button : most of them are the same; &hange the following properties of your label, #ust like you did for the button0 Location0 32, 52 Text0 )ame You don't really need to set a si<e, because %isual &' will automatically resi<e your label to fit your text. ut your (orm should look like this0
=ove your mouse back over to the Toolbox. &lick on the TextBox entry. Then click on your form. * new Text ox will be added, as in the following image0
Instead of setting a location for your text box, simply click it with your left mouse button. >old your left mouse button down, and the drag it #ust to the right of the $abel. )otice that when you drag your text box around, lines appear on the form. These are so that you can align your text box with other controls on the form. In the image below, we've aligned the text box with the left edge of the button and the top of the $abel.
+,, time to add some code. efore you do, click File > Save ll from the menu bar at the top of %isual &'. You can also run your programme to see what it looks like. Type some text in your text box, #ust to see if it works. )othing will happen when you click your button, because we haven't written any code yet. $et's do that now. &lick the red ? on your form to halt the programme, and you'll be returned to %isual &'.
)otice all the minus symbols on the left hand side. You can click these, and it will hide code for you. &lick the minus symbol next to !ublic Form"# $. It will turn into a plus symbol, and the code for #ust this =ethod will be hidden0
>iding code like this makes the rest of the coding window easier to read. ack to the button code, though. !e're going to set up a string variable. To do this, you need two things0 the Type of variable you want, and a name for your variable. &lick inside the two curly brackets of the button code, and add the following0 string %irstNameA *fter the semi:colon, press the enter key on your keyboard to start a new line. Your coding window will then look like this0
!hat you have done is to set up a variable called %irstName. The Type of variable is a string. )ote that the coding editor will turn the word BstringB blue. lue denotes the variable type : a string, in this case. -+ther variable types are int, %loat, and &ouble. These are all number variables that you'll meet shortly./
*fter you have told &' which type of variable you want, you then need to come up with a name for your variable. This is like the sticker on an empty box. The empty box is the variable type. Think of these empty boxes as being of different si<es and different materials. * big, cardboard box is totally different from a small wooden one; ut what you are really doing here is telling &' to set aside some memory, and that this storage area will hold strings of text. You give it a uni.ue name so as to tell it apart from other items in memory. *fter all, would you be able to find the correct box, if they were all the same si<e, the same shape, the same colour, and had no stickers on themC The name you pick for your variables, %irstName in our case, can be almost anything you want : it's entirely up to you what you call them. ut you should pick something that is descriptive, and gives you a clue as to what might be in your variable. !e say you can call your variables almost anything. ut there are some rules, and some words that &' bags for itself. The words that &' reserves for itself are called ,eywords. There are about D2 of these words, things like using, %or, new, and !ublic. If the name you have chosen for your variable turns blue in the coding window, then it's a reserved word, and you should pick something else.
*fter setting up your variable -telling &' to set aside some memory for you/, and giving it a name, the next thing to do is to store something in the variable. *dd the following line to your code -don't forget the semi:colon on the end/0 %irstName , textbox"-Text. Your coding window will then look like this0
To store something in a variable, the name of your variable goes on the left hand side of an e/uals sign. *fter an e.uals sign, you type what it is you want to store in the variable. (or us, this is the Text from textbox". Fxcept, there's a slight problem. Try to run your code. You should see an error message like this one0
There is a blue wiggly line under textbox3. >old your mouse over this and %isual "tudio will tell you that0 T'e name 0textbox"0 &oes not exist in t'e current contextIf you see an error like this, which is .uite common, it means that %isual &' cannot find anything with the name you've #ust typed. "o it thinks we don't have a textbox called textbox3. *nd we don't; It's called text ox3. !e've typed a lowercase BbB when it should be an uppercase B B. "o it's important to remember that &' is case sensitive. This variable name0 %irstName Is different to this variable name0 FirstName The first one starts with a lowercase BfB and the second one starts with an uppercase B(B. 9elete the lowercase BbB from your code and type an uppercase B B instead. Gun your programme again and you won't see the error message. )ow stop your programme and return to the coding window. The blue wiggly line will have disappeared. !hat have so far, then, is the following0 string %irstName. %irstName , textBox"-Text. The first line sets up the variable, and tells &' to set aside some memory that will hold a string of text. The name of this storage area will be %irstName. The second line is the one that actually stores something in the variable : the Text from a text box called textBox". )ow that we have stored the text from the text box, we can do something with it. In our case, this will be to display it in a message box. *dd this line to your code0 1essageBox-S'ow#%irstName$. The =essage ox."how- / =ethod is one you've #ust used. In between the round brackets, you can either type text surrounded by double .uotes, or you can type the name of a string variable. If you're typing the name of a variable, you leave the double .uotes off. You can do this because &' knows what is in your variable -you have #ust told it on the second line of your code./
Gun your programme again. Type something in your text box, and then click the button. You should see the text you typed0
10
Gun your programme again. Type something in the text box, your own first name. Then click the button. You should see two message boxes, one after the other. The first one will display your first name. ut the second will display B>ome and $earnB. !e're using the same variable name, here0 %irstName. The first time we used it, we got the text directly from the text box. !e then displayed it in the =essage ox. !ith the two new lines, we're typing some text directly in the code, B>ome and $earnB, and then assigning that text to the %irstName variable. !e've then added a second =essage ox."how- / method to display whatever is in the variable. In the next part of this lesson, you'll learn about something called &oncatenation.
Concatenation in C#
@@ &ontinues from previous lesson *nother thing we can do is something called &oncatenation. &oncatenation is #oining things together. You can #oin direct text with variables, or #oin two or more variables to make a longer string. * coding example may clear things up. 9elete the two new lines you've #ust added. )ow add a second variable, #ust below the first one0 string messageText. "o you coding window should look like this0
11
!e want to store some text inside of this new variable, so add the following line of code #ust below string messageText0 messageText , 24our name is5 2. Your code window will then look like ours below0
!hen the message box displays, we want it say some thing like BYou name is HohnB. The variable we've called messageText holds the first part of the string, BYour name is B. *nd we're getting the persons name from the text box0 %irstName , textBox"-Text. The person's name is being stored in the variable called %irstName. To #oin the two together -concatenate/ &' uses the plus symbol - I /. messageText 6 %irstName Instead of #ust %irstName between the round brackets of =essage ox."how- /, we can add the messageText variable and the plus symbol0 =essage ox."how-messageText 6 %irstName/A *mend your =essage ox line so it's the same as the one above. >ere's the coding window0
12
Gun your programme. Type your first name into the text box, and then click your button. You should see something like this0
"o we set up a variable to hold some direct text, and got the person's name from the text box. !e stored this information in two different variables. To #oin the two together, we used the plus symbol. !e then displayed the result in a message box. ut you can also do this0 1essageBox-S'ow# 24our name is5 2 6 %irstName$. >ere, we're not storing the text in a variable called messageText. Instead, it's #ust direct text surrounded by double .uotes. )otice, though, that we still use the plus symbol to #oin the two together.
Comments in C# -N7T
@@ &ontinues from previous lesson You don't have to use a message box to display the result. You can use other controls, like a $abel. $et's try it. *dd a new $abel to your form. Jse the Properties !indow to set the following properties for your new $abel0
13
Name0 Text=essage Location0 D4, 36K Text0 =essage *rea Geturn to your coding window, and add two forward slashes to the start of your =essage ox."how- / line. The line should turn green, as in the following image0
The reason it turns green is that two forward slashes are the characters you use to add a comment. &' then ignores theses lines when running the programme. &omments are a very useful way to remind yourself what the programme does, or what a particular part of your code is for. >ere's our coding window with some comments added0
You can also use the menu bar, or the toolbar, to add comments. >ighlight any line of text in your code. (rom the menu bar at the top of %isual &', select 7&it > &vance& > Comment Selection. Two forward slashes will be added to the
14
start of the line. You can .uickly add or remove comments by using the toolbar. $ocate the following icons on the toolbars at the top of %isual &'0
The comment icons are circled in red, in the images above. The first one adds a comment, and the second one removes a comment. -If you can't see the above icons anywhere on your toolbars, click View > Toolbars > Text 7&itor./ )ow that you have commented out the =essage ox line, it won't get executed when your code runs. Instead, add the following like to the end of your code0 Text1essage-Text , messageText 6 %irstName. Your coding window should then look like this0
Gun your programme again. Type your name in the text box, and then click your button. The message should now appear on your label, instead of in a =essage ox0
15
The reason is does so is because you're now setting the Text property of the $abel with code. Previously, you changed the $abel's Text Property from the Properties !indow. The name of our label is Text1essage. To the right of the e.uals sign, we have the same code that was in between the round brackets of the "how- / method of the =essage ox. +,, time for an exercise.
7xercise *dd a second text box to your form. 9isplay your message in the text box as well as on the label. "o if your name is Hohn, your second text box should have0 BYour name is0 HohnB in it after the button is clicked. !hen you complete this exercise, your form should look like this, when the button is clicked0
16
!eLre now going to move away from string variables and on to number variables. The same principles youLve #ust learnt still apply, though0
"et up a variable, and give it a name "tore something in the variable Jse code to manipulate what you have stored
C# 9ntegers
17
*n integer is a whole number. It's the K of K.5, for example. In programming, you'll work with integers a lot. ut they are #ust variables that you store in memory and want to manipulate. You'll now see how to set up and use Integer variables. *dd a button to your form, and set the following properties for it in the Properties !indow0 Name0 btnIntegers Text0 Integers Location0 332, 62 )ow double click your button to get at the code0
In the previous section, you saw that to set up a string variable you #ust did this0 string myTextA You set up an integer variable in the same way. Fxcept, instead of typing the word string, you type the word int -short for integer/. "o, in between the curly brackets of your button code, type int. You should see the word turn blue, and the Intelli"ense list appear0
18
Fither press the enter key on your keyboard, or #ust hit the spacebar. Then type a name for your new variable. &all it m(9nteger. *dd the semi:colon at the end of your line of code, and hit the enter key. Your coding window will then look like this0
)otice the text in the yellow box, in the image one up from the one above. It says0 :e!resents a ;*<bit signe& integer * signed integer is one that can have negative values, like :5, :K, etc. -The opposite, no negative numbers, is called an unsigned integer./ The 76:bit part is referring to the range of numbers that an integer can hold. The maximum value that you can store in an integer is0 6,3M4,MD7,KMD. The minimum value is the same, but with a minus sign on the front0 :6,3M4,MD7,KMD. To store an integer number in your variable, you do the same as you did for string0 type the name of your variable, then an e.uals sign - N /, then the number you want to store. "o add this line to your code -don't forget the semi:colon on the end/0 m(9nteger , *=. Your coding window should look like this0
19
"o we've set up an integer variable called myInteger. +n the second line, we're storing a value of 65 inside of the variable. !e'll use a message box to display the result when the button is clicked. "o add this line of code for line three0 =essage ox."how-m(9nteger/A )ow try to run your code. You'll get the following error message0
You should see a blue wiggly line under your =essage ox code0
>old your mouse over m(9nteger, between the round brackets of S'ow- /. You should see the following yellow box0
20
The error is0 B&annot convert from int to stringB. The reason you get this error is because m(9nteger holds a number. ut the =essage ox only displays text. &' does not convert the number to text for you. It doesn't do this because &' is a programming language known as Bstrongly typedB. !hat this means is that you have to declare the type of variable you are using -string, integer, double/. &' will then check to make sure that there are no numbers trying to pass themselves off as strings, or any text trying to pass itself off as a number. In our code above, we're trying to pass m(9nteger off as a string. *nd &' has spotted it; !hat you have to do is to convert one type of variable to another. You can convert a number into a string .uite easily. Type a full stop -period/ after the BrB of myInteger. You'll see the Intelli"ense list appear0
"elect ToString from the list. ecause ToString is a method, you need to type a pair of round brackets after the BgB of To"tring. Your code will then look like this -we've highlighted the new addition/0
The To"tring method, as its name suggests, converts something to a string of text. The thing we are converting is an integer. "tart your programme again. ecause you've converted an integer to a string, you should find that it runs +, now. &lick your button and you should see the message box appear0
21
In the next lesson, we'll take a look at double variables, and float variables.
22
To get some practice using floats and doubles, return to your form. If you can't see the Form"-cs ?>esign@ tab at the top, right click (orm3.cs in the "olution Fxplorer on the right hand side. -If you can't see the "olution Fxplorer, click %iew P "olution Fxplorer from the menu bar at the top./
*dd a new button to your form. "et the following properties for it in the Properties !indow0 Name btn(loat Location0 332, 45 Text0 (loat 9ouble click your new button, and add the following line to the button code0 float my(loatA Your coding window will then look like this0
23
To store something inside of your new variable, add the following line0 m(Float , A-B*F. The capital letter ( on the end means (loat. You can leave it off, but &' then treats it like a double. ecause you've set the variable up as a float, you'll get errors if you try to assign a double to a float variable. *dd a third line of code to display your floating point number in a message box0 =essage ox."how- m(Float-ToString# $ /A *gain, we have to use To"tring- / in order to convert the number to a string of text, so that the message box can display it. ut your coding window should look like ours below0
Gun your programme and click your (loat button. You should see a form like this0
24
>alt the programme and return to your coding window. )ow delete the capital letter ( from 2.M6. The line will then be0 m(Float , A-B*. Try to run your programme again. You'll get an error message, and a blue wiggly line under your code. ecause you've missed the ( out, &' has defaulted to using a double value for your number. * float variable can't hold a double value, confirming that &' is a strongly typed language. -The opposite is a weakly typed language. P>P, and Hava"cript are examples of weakly typed languages : you can store any kind of values in the variables you set up./ *nother thing to be careful of when using float variables is rounding up or down. *s an example, change the number from 2.M6( to 367M.5K4(. )ow run your programme, and click your float button. The message box will be this0
>alt the programme and return to your code. )ow add an D before the ( and after the 4, so that your line of code reads0 m(Float , "*;B-=CDEF.
25
)ow run your programme again. !hen you click the button, your message box will be this0
It's missed the 4 out; The reason for this is that float variables can only hold 4 numbers in total. If there's more than this, &' will round up or down. * number that ends in 5 or more will be rounded up. * number ends in 5 or less will be rounded down0 "*;B-=CDE -eight numbers ending in D : round up/ "*;B-=CDB -eight numbers ending in M : round down/ The number of digits that a variable can hold is known as !recision. (or float variable, &' is precise to 4 digits0 anything more and the number is rounded off. In the next part, we'll take a closer look at doubles
26
Gun your programme and click your new button. You should see this0
You also need to be careful of precision when using double variable types. The double type can hold up to 3K digits. >alt your programme and return to the coding window. &hange this line0 m(>ouble , A-AAD. to this0 m(>ouble , "*;B=CDE-"*;B=CD. Gun your programme and click your double button. The message box correctly displays the number. *dd another number on the end, though, and &' will again round up or down. The moral is, if you want accuracy, careful of rounding; In the next part, you'll see how to add up in &'.
&&ition in C# -N7T
27
!e'll now use variables to do some adding up. *fter you have learned how to add up with the three number variable types, we can move on to subtraction, multiplication, and division. "tart a new pro#ect for this. "o click File > Close Solution from the menu bar at the top of %isual &'. Then click File > New Project. Type arit'metic as the )ame of your new !indows (orms *pplication pro#ect.&lick +, to create the new pro#ect. *dd a button to your new form, and set the following properties for it in the Properties !indow0 Name0 btn*dd Size0 322, 72 Text0 Integer : *dd =ove the button to the top of your form. Then double click it to get at the coding window. "et up the following three integer variables in your button code0 int first)umberA int second)umberA int integer*nswerA Your coding window should look like ours below0
!e now need to put something into these variables. !e'll store 32 in the first number, and 76 in the second number. "o add these two lines to your code0 %irstNumber , "A. secon&Number , ;*. Your coding window will then look like this0
28
"o the numbers we want to store in the variables go on the right hand side of the e.uals signA the variable names go on the left hand side of the e.uals sign. This assigns the numbers to the variables : puts them into storage. !e now want to add the first number to the second number. The result will be stored in the variable we've called integer nswer. (ortunately, &' uses the plus symbol -I/ to add up. "o it's fairly simple. *dd this line to your code0 integer nswer , %irstNumber 6 secon&Number. *nd here's the coding window0
!e've already stored the number 32 in the variable called %irstNumber. !e've stored 76 in the variable secon&Number. "o we can use the variable names to add up. The two variables are separated by the plus symbol. This is enough to tell &' to add up the values in the two variables. The result of the addition then gets stored to the left of the e.uals sign, in the variable called integer nswer. Think of it like this0
29
To see if all this works or not, add a message box as the final line of code0 1essageBox-S'ow# integer*nswer.To"tring- / $. !e're #ust placing the integer nswer variable between the round brackets of "how- /. ecause it's a number, we've had to use To"tring- / to convert the number to text. >ere's what your coding window should look like now0
30
You don't have to store numbers in variables, if you want to calculate things. You can #ust add up the numbers themselves. $ike this0 integer nswer , "A 6 ;*. *nd even this0 integer nswer , %irstNumber 6 ;*. "o you can add up #ust using numbers, or you can mix variable names with numbers. *s long as &' knows that there's a number in your variable, and that it's the right type, the addition will work.
31
You can use more than two variables, or more than two numbers. "o you can do this0 integer nswer , %irstNumber 6 secon&Number 6 t'ir&Number. or this0 integer nswer , %irstNumber 6 secon&Number 6 ;*. *nd this0 integer nswer , %irstNumber 6 "A 6 ;*. The results is the same0 &' adds up whatever you have on the right hand side of the e.uals sign, and then stores the answer on the left hand side. In the next part, you'll see how to add up with float variables.
32
-)otice that we've used the same names for the first two variables. &' doesn't get confused, because they are in between the curly brackets of the button code. You can set up variables outside of the curly brackets. !e'll do this when we come to code the calculator, at the end of this section. Then something called scope comes in to play. 9on't worry about it, for now./ To place something in your new variables, add the following code0 %irstNumber , "A-=F. secon&Number , ;*-=F. %loat nswer , %irstNumber 6 secon&Number. (inally, add you message box line0 1essageBox-S'ow# %loat nswer-ToString# $ $. The coding window should look like this0
Gun your form and click your new button. You should see this0
33
"o 32.5 I 76.5 e.uals M7. >alt your form by clicking the red ?, and return to your coding window. *s was mentioned, you can add float and integer values together. ut you need to take care. Try this0 *dd the following variable to your code0 int integer*nswerA *nd then change this line0 %loat nswer , %irstNumber 6 secon&Number. To this0 integer nswer , %irstNumber 6 secon&Number. "o it's #ust the name of the variable before the e.uals sign that needs to be changed. *mend you message box line from this0 1essageBox-S'ow# %loat nswer-ToString# $ $. To this0
34
1essageBox-S'ow# integer nswer-ToString#$ $. Your coding window will then look like this0
Try to run your code. The programme won't execute, and you'll have a blue wiggly line0
>old your mouse over the blue wiggly line and you'll see an explanation of the error0
)ot much help, if you're a beginner; ut what it's telling you is that the first number and the second number are float variables. The answer to the addition was also a float. >owever, you were trying to store the answer in an integer variable. &' won't let you store float values in an integer. The error message is saying that you need to convert them first.
35
You can indeed convert float values to integers. You do it like this0 integer nswer , #int$ %irstNumber 6 #int$ secon&Number. "o you type the word int between a pair of round brackets. This goes before the number you want to convert. It does mean that the point something on the end will get chopped off, though. "o 32.5 becomes 32, and 76.5 becomes 76. )ot good for accuracy, but at least the programme will run; Try it out, and you should see an answer of M6 when you click your button. "o the moral is this0 If you're expecting an answer that ends in point something, use a float variable -or a double/. -You may have a green wiggly line under float %loat nswer. This is because you're not storing anything in this variable. 9on't worry about it;/ )ote that the other way round is not a problem : you can store an integer in a float value. >ave a look at this slight change to the code0
(irst, notice the new way we are storing the number 62 into the integer variable called integer nswer0 int integer*nswer N 62A Instead of two lines, we've #ust used one. This is fine, in &'. ut you're doing two things on the same line0 setting up the variable, and placing a value in it. The second thing to notice is that we are adding up two float values -first)umber and second)umber/ and an integer -integer*nswer/. !e're then storing the answer into a float variable -float*nswer/. Try it out and you'll find that the code runs fine. 36
If we change this line0 %irstNumber , "A-=F. to this0 %irstNumber , "A. then, again, the programme will run fine. In other words, you can store an integer in a float variable, but you can't store a float value in an integer variable without converting. >opefully, that wasn't too confusing; !e'll move on to subtraction, now. ut if you want to use a double variable instead of a float variable the same things apply : be careful of what you are trying to store, and where;
Subtraction in C# -N7T
@@ &ontinues from the previous lesson "ubtraction is fairly straightforward in &'. To subtract one number from another, you use the minus symbol - : /. *dd another button to your form. "et the following properties for it in the Properties !indow0 Name5 btnSubtract Size5 "AAF ;A> Text5 Subtract 9ouble click the button to get at the code. *dd the following three lines of code0 int answerSubtractA answerSubtract , =A < *=. 1essageBox-S'ow# answerSubtract-ToString#$ $. Your coding window will then look like this0
37
"o we've set up an integer variable called answerSubtract. +n the second line, we're using the minus symbol to subtract 65 from 52. !hen &' works out the answer to 52 : 65, it will place the answer to the left of the e.uals sign, in the answerSubtract variable. +n the final line, we're displaying the answer in a message box. Gun your code, and make sure it works. The answer you should see in the message box is, of course, 65. "top your programme and return to the coding window. )ow change the 65 to 65.5. answerSubtract , =A < *=-=. Try to run your programme and you'll get the blue wiggly line, meaning there's an error in your code. The reason is the same as for addition0 we're trying to place a float number into an integer variable -the answer will be 6M.5, this time/. Hust because the math symbol has changed doesn't mean we can disobey the &' rules; &hange it back to 65, and the code will run fine. *s with addition, you can subtract more than one number. &hange your line to this0 answerSubtract , =A < *= < "A < *. !hen you run your programme, you should see 37 in your message box, the answer to the subtraction. You can also use variable names in your subtraction. *dd the following integer variable to your code0 int number+ne N 36A Then change the second line to this0 answerSubtract , =A < numberGne.
38
!hat we're doing here is setting up an integer variable called numberGne. !e're then placing a value of 36 inside of the variable : all on the same line. (or the second line, we're subtracting whatever is in the variable called numberGne from 52. Gun you programme and click your button. You should see an answer of 7D in your message box.
7xercise "et up another variable. &all it numberTwo. Place a value of M inside of this new variable. "ubtract from 52 the value in numberGne and the value in numberTwo. !hen you run your code, the answer you get in the message box should be 7M. *nswer to Fxercise *
39
Name0 btn=ixed Size0 322, 72 Text0 *dd and "ubtract -If you need to make your (orm bigger, click on the form to select it. Then change the "i<e property in the Properties !indow./ 9ouble click your button to get at the code. !e'll need four integer variables for this. "o set up the following0 int %irstNumber. int secon&Number. int t'ir&Number. int answer. To place values in the variables, add the following three lines0 %irstNumber , "AA. secon&Number , D=. t'ir&Number , =A. Your coding window will then look like this0
To add the first number to the second number, and then place the result in the variable we've called answer, add the following line to your code0 answer , %irstNumber 6 secon&Number. 9isplay the answer in a message box by adding this line0 1essageBox-S'ow# answer.To"tring- / $. !hen you run the programme and click your button, you should see the message box display an answer of 345.
40
"top the programme and return to your code. !e now want to subtract the third number from the first two. "o change this line0 answer , %irstNumber 6 secon&Number. to this0 answer , %irstNumber 6 secon&Number < t'ir&Number. !hen &' sees all these variables after the e.uals sign, it will try to calculate using the numbers you've stored in the variables. Jsually, it will calculate from left to right. "o this bit gets done first0 %irstNumber 6 secon&Number !hen &' finishes adding the first two numbers, it will then deduct the value in t'ir&Number. The answer is then stored in the variable to the left of the e.uals sign. Gun your programme. !hen the button is clicked, the message box will display an answer of 365. "o mixing addition and subtraction is fairly straightfoward : #ust use the I and : symbols. >owever, there can be problems; In the next part, you'll about something called +perator Precedence.
41
Then when the answer to that is found, add the t'ir&Number. "o the sum is this0 322 : 45, which e.uals 65. Then 65 I 52, which e.uals 45. ut what if you didn't mean thatC !hat if you wanted %irstNumber minus the answer to secon&Number 6 t'ir&NumberC In case that's not clear, some brackets may help clear things up. >ere's the two ways of looking at our calculation0 # %irstNumber < secon&Number $ 6 t'ir&Number %irstNumber < # secon&Number 6 t'ir&Number $ In maths, brackets are a way to clear up your calculations. In the first one, whatever is between the round brackets is calculated first. The total of the sum in brackets is then added to t'ir&Number. In the second one, it's the other way around0 second)umber is first added to third)umber. You then deduct from this total the value of first)umber. You can use brackets in programming, as well. *dd the following brackets to your code0 answer , %irstNumber < #secon&Number 6 t'ir&Number$. Your coding window should then look like this0
!hen you run your programme and click the button, this time the answer is minus 65. Previously, the answer was 45; The reason the answer is different is because you've used brackets. &' sees the brackets and tackles this problem first. The next thing it does is to deduct %irstNumber from the total. !ithout the brackets, it simply calculates from left to right.
42
H =ultiply I 9ivide
&hange your code to this0 answer , # %irstNumber 6 secon&Number $ H t'ir&Number. ecause of the brackets, the first thing that &' does is to add the value in %irstNumber to the value in secon&Number. The total is then multiplied - Q / by the value in t'ir&Number. !ith the values we currently have in the variables, the sum is this0 answer , # "AA 6 D= $ H =A Gun your programme and click your button. The answer you should get is D452. Geturn to the coding window. )ow remove the two round brackets. Your coding window will then be this0
Gun your programme again. &lick the button. This time, the answer is 7D52; The reason it's different is because of +perator Precedence. !ith the brackets, you forced &' to calculate the addition first. !ithout the brackets, &' no longer calculates from left to right. "o it's )+T doing this0 # "AA 6 D= $ H =A
43
&' sees multiplication as having priority over addition and subtraction. "o it does the multiplying first. It does this0 "AA 6 # D= H =A $ The two give you totally different answers. The same is true of division. Try this. *mend your line of code to the following0 answer , # %irstNumber 6 secon&Number $ I t'ir&Number. Gun the programme and the answer will be 7. -The real answer to -322 I 45/ R 52 is, of course, 7.5. ut because we're using integer variables and not floats, the point something at the end gets chopped off./ "o we're using the divide symbol now - R /, instead of the multiplication symbol -Q/. The addition is done first, because we have a pair of round brackets. The total of the addition is then divided by the value in third)umber. Geturn to the code, and change the line to this0 answer , %irstNumber 6 secon&Number I t'ir&Number. "o #ust remove the round brackets. Gun your programme again, and you'll find that the answer in the message box is now 323. -It would have been 323.5, if we had used a float variables instead of integers./ If you now replace the plus symbol - I / above with a multiplication symbol - Q /, &' switches back to Bleft to rightB calculation. This is because it sees division and multiplication as having e.ual weight. The answer you'll get without brackets is 352. 7xercise B Try the following two lines. (irst this one answer , #%irstNumber H secon&Number$ I t'ir&Number. *nd now this one0 answer , %irstNumber H #secon&Number I t'ir&Number$. !hat answer do you get with the round brackets in different placesC &an you understand whyC If not, go back over this section.
!e're going to change tack slightly, here. !hat we'll do is show you how to get numbers from text boxes, and then use these numbers in your code. You'll need to be able to do this for your calculator pro#ect, which is coming up soon; "tart a new pro#ect for this one by clicking File > New Project from the menu bar at the top of %isual &'. *dd a text box and a button to your new form. "et the following Properties for the text box -the tb below stands for text box/0 Name0 tb(irst)umber Size0 52, 62 Location0 M2, 75 Text0 32 *nd set the following properties for your button0 Name0 btn*nswer Size0 45, 65 Location0 12, 12 Text0 *nswer Your form will then look like this0
!hat we want to do is to get that number 32 from the text box and display it in a message box.
45
"o double click your button to get at the coding window. Your cursor will be flashing inside of the button code. "et up two integer variables at the top of the button code0 int %irstTextBoxNumber. int answer. Your coding window should look like this0
To get at the number in the text box, we can use the Text property of text boxes. >ere's the line of code to add0 %irstTextBoxNumber , tbFirstNumber-Text. This says, find a text box called tbFirstNumber. *ccess its Text property. !hen the Text property is retrieved, store it in the variable called %irstTextBoxNumber. To display the number in a message box, add this line0 1essageBox-S'ow# %irstTextBoxNumber-ToString# $ $. Try to Gun your code. You should find &' won't run it at all. It will give you the following error0
!ith text boxes, the thing that you get is, not surprisingly, text. >owever, we're trying to store the text from the text box into an integer variable. &' won't let you do this : whole numbers belong in integer variables, not text. The error message
46
is telling you that &' can't do the conversion from text to numbers for you : you have to do it yourself; "o we need to convert the text from the text box into an integer. The way you do this is to use something called Parsing. (ortunately, this involves nothing more complex that typing the word BParseB. You can do different types of Parses. ecause we need to convert the text into an integer, we need an Integer Parse. "o change the line to this0 %irstTextBoxNumber , int-Parse# tbFirstNumber-Text $. "o you type int, then a full stop. (rom the Intelli"ense menu, you can double click Parse. In between a pair of round brackets, you type the text you want to convert. In our case, the text is coming from a text box. ut it doesn't have to. You can do this0 %irstTextBoxNumber , int-Parse# 2"A2 $. In the code above, the number is in double .uotes. 9ouble .uotes mean that it is text. Jsing int-Parse# $ means that it will be converted to a number that you can store in an integer variable. Gun your programme and you'll find that it works +, now. -You'll have a green wiggly line under answer, but that's #ust because we haven't used this variable yet./ &lick your button and the number 32 will appear in the message box. Type a different number in your text box, and click the button again. The new number should appear in place of the old one. You can also Parse other types of variable. $ike this0 %loat %irstTextBoxNumber. %irstTextBoxNumber , %loat-Parse# tbFirstNumber-Text $. +r this0 &ouble %irstTextBoxNumber %irstTextBoxNumber , &ouble-Parse# tbFirstNumber-Text $. In the first one, we've set up a float variable. !e've then used %loat-Parse# $ to convert the text from the text box, so that it can be stored in the float variable. !e've done exactly the same thing in the second example, to convert the text into a double. Things get more complicated if you accidentally try to store a double value in a float variable : your programme will crash; You need to try to catch things like this with code. -You'll see how to test for errors like this later in the book./
47
(or now, let's move on. +,, so we've got text from a text box and displayed it in a message box. !hat we'll do now is to add a second text box, get numbers from both, use our =ath operators, and do some calculations with the two number we took from the text boxes. "ounds complex, but it isn't; *dd a second text box to your form. "et the following Properties for it in the Properties !indow0 Name0 tb"econd)umber Size0 52, 62 Location0 3K5, 75 Text0 5 Your form will then look like this0
9ouble click the button to get at your code. )ow set up another integer variable to hold the second number from the new text box0 int secon&TextBoxNumber. To store the number from the text box in this new variable, add the following line0 secon&TextBoxNumber , int-Parse# tbSecon&Number-Text $. This is the same as before : use int-Parse to convert the number from the text box into an integer variable. Then store the number in the new variable.
48
$et's add the two numbers up, first. !e can use the answer variable for this. >ere's the code to add0 answer , %irstTextBoxNumber 6 secon&TextBoxNumber. "o we're #ust using the plus symbol - I / to add up whatever is in the two variables. The numbers in the variables come from the two text boxes. *mend your message box line to this0 1essageBox-S'ow# answer.To"tring- / $. *ll you need to do is to change the name of the variable that your are converting To"tring- /. Your coding window should look like ours0
Gun your programme, and then click the button. You should the answer to the addition in your message box0
49
&hange the numbers in the text boxes, and click your button again. !hen you've finished playing with your new form, click the red ? to return to the code. >ere are a few exercises for you to try.
7xercise Jse the textboxes on your form to calculate the following -you'll need to amend your code for three of them/0 3DM5 I 6D5D 7M52 : 6D5 75 Q D5 5K5K R 4 -The answers you should get are0 M427, 73K5, 6145 and D2D./
7xercise *dd a new text box to you form. "et up an integer variable to store a third number. 8et the third number from the text box and calculate the following0 -3DM5 I 6D5D/ : 75K -7M52 : 6D5/ Q 36 75 Q - D5 : D / -5K5K R 4/ I 635K
50
-The answers you should get are0 M7M4, 741D2, 6K15 and 61KM. You'll have to keep closing the form down. Then add round brackets, the operator symbols, and the new variable./ +nce you've completed the exercises, you can move on to tackling the next pro#ect : your very own calculator;
*s you can see, it has a text box for the display of numbers, buttons for the numbers 2 to 1, a point symbol, plus and e.uals buttons, and a clear button.
51
"o the first thing to do is to design your calculator. "tart a new pro#ect by clicking (ile P )ew pro#ect. (or your new form, set the following properties0 Size0 MM2, MD4 Text0 &alculator To add a bit of colour to your calculator, you can change the ack&olour property of the form, as in the image below0
!e went for an orange colour, but feel free to choose any colour you like. )ow add a text box to your form and set the following properties for it0 Name0 txt9isplay Location0 KK, 56 Size0 622, 6K Text lign0 Gight Time to add the buttons. You need 32 buttons for the numbers 2 to 1. *dd the first button to the form, and set the following properties for it0 Name0 btnSero Font0 =icrosoft "ans "erif, old, 36 52
Location0 3M7, 74D Size0 M1, M2 Text0 2 This is the <ero button, which goes at the bottom. *dd a new button to your form and set the following properties for it0 Name0 btn+ne Font0 =icrosoft "ans "erif, old, 36 Location0 KK, 351 Size0 M1, M2 Text0 3 *n easier way to add new buttons, is to copy and paste them. &lick on btnGne to select it. Gight click the button and select Co!( from the menu that appears. )ow click anywhere on the form. Gight click again, and select Paste. * new button will appear with the number 3 on it. >ave a look at the properties window, though, and you'll see that the new button has the )ame button3. &hange it to btnTwo. Then change the Text property to *. 9rag it in to position next to your number 3 button. *dd the other number buttons in the same0 &opy, Paste, change the Name and the Text properties. (or the other number buttons, use the following for the )ame properties0 btnThree, btn(our, btn(ive, etc. Position your buttons like ours. *dd a new button for the Point symbol. 8ive it the )ame btnPoint, and type a full stop -period/ for the Text property. &hange the (ont property, if you think it's too small. +nly three buttons to go. "o add three more buttons, and use the following properties0 Name0 btnPlus Font0 =icrosoft "ans "erif, old, 36 Location0 76M, 351 Size0 M1, M2 Text0 I Name0 btnF.uals Font0 =icrosoft "ans "erif, old, 36 Location0 76M, 672 Size0 M1, M2 Text0 N Name0 btn&lear Font0 =icrosoft "ans "erif, old, D
53
Location0 76M, 725 Size0 M1, M2 Text0 &lear &hange the locations, though, if they don't match the alignment for your own buttons. ut you've now completed the design of your calculator. "ave your hard work, and we can begin the coding in the next part.
know what was in there before, and discards the number that you previously stored. >alt your programme and return to your code. &hange your line to this0 txt>is!la(-Text , txt>is!la(-Text 6 btnGne-Text. This line is easier to read if you #ust look at the part after the e.uals sign. !hich is this0 txt>is!la(-Text 6 btnGne-Text. !hen you're working with text, the plus symbol doesn't mean add : it means concatenate -you learned about this in the previous section when working strings/. "o &' will #oin the text in the text box with the text on the button. *fter it has finished doing this, it will store the answer to whatever is on the left of the e.uals sign. In this case, it's not a variable but the text property of the text box. Gun your programme again. &lick the number one button a few times. You should find that the number one will appear in the text box more than once. >alt the programme and return not to your code but to the form itself. -If you can't see your form, right:click Form"-cs in the "olution Fxplorer on the right. (rom the menu that appears, select View >esigner./ )ow double click button 6, and add the following code0 txt9isplay.Text N txt9isplay.Text I btnTwo.TextA The only thing that's different is the name of the button : btnTwo instead of btnGne. The rest is the same. 9o the same for the rest of your button, changing the name of the button each time. -You can copy and paste your code to save time./ ut your coding window should look like this, when you've finished0
55
Gun your programme again, and click all ten of your buttons. =ake sure that each number appears in the text box when its button is clicked.
56
Geturn to your form and double click the Clear button. *dd the following line0 txt9isplay.Clear# $A *fter the full stop, you type the word Clear, followed by a pair of round brackets. &lear is a method you can use on text boxes. *s its name suggests, it will clear the text box, leaving it blank. Gun your programme again, click a few numbers, then try your &lear button. The numbers should disappear from the text box. In the next part, we'll add the code for the Plus button.
57
we need to give it what's knows as global scope. This is fairly easy : #ust set it up outside of any buttons. $ike this0 &ouble total" , A. !rivate voi& btnPlus)ClicK#object sen&erF 7vent rgs e$ L M )ow the variable is outside of the curly brackets, making it available to all the buttons on out form. "o set up that variable in your own code. (or the btnPlus code itself, add the following two lines -in blue bold below/0 &ouble total" , A. !rivate voi& btnPlus)ClicK#object sen&erF 7vent rgs e$ L total" , total" 6 &ouble-Parse# txt>is!la(-Text $. txt>is!la(-Clear#$. M *ll we're doing here is getting the text from the text box, converting it to a double number, and then storing it in the total3 variable. )otice that we've also done this0 total" , total" 6 Hust like we did for the number buttons, we need to keep whatever was in the total" variable. You need to do this in case you want to add more than two numbers. If you didn't keep what was in the total3 variable, &' would BforgetB what was in it, and start afresh. This techni.ue is so common in programming that a shorthand way of doing this is usually implemented0 total" 6, &ouble-Parse#txt>is!la(-Text$. "o instead of repeating the variable name, you #ust use a plus symbol and an e.uals symbol together - IN /. The above line does exactly the same thing as this0 total" , total" 6 &ouble-Parse#txt>is!la(-Text$. ut whichever way you choose to retain a value in a variable, all you're saying is B,eep whatever is already in the variable, and add something elseB.
58
*fter storing the number from the text box, we need to clear it0 txt>is!la(-Clear# $. +nce the text box is cleared, a second number can be selected by clicking the number buttons. In the next part, you'll learn how to code for the F.uals button.
59
total" 6 &ouble-Parse#txt>is!la(-Text$. The difference is before the e.uals sign0 we're now storing it in the total6 variable0 total* N total3 I double.Parse-txt9isplay.Text/A In other words, get the number from the text box, convert it to a double variable, add it to whatever is in total3. !hen all this is worked out, store the answer in the variable called total6. The second line of code was this0 txt>is!la(-Text , total*-ToString# $. +n the right of the e.uals sign, we're converting the total* variable To a "tring. This is so that it can be displayed as Text in the text box. The third line of code resets the total3 variable to <ero0 total" , A. This is so a new sum can be calculated. Time to try out your calculator. Jse it to calculate the following0 "A 6 *= ;C 6 ;C "A 6 "A 6 "A +f course, you can do these sums in your head. ut make sure that your calculator gets its sums right before going any further. &lick your Clear button to start a new addition. !hen you're sure you understand what is going on with the code, try this exercise. 7xercise C You have not yet written any code for the btnPoint button. This means that you can't have numbers like 32.5 or 7K.4 in your additions. !rite code to solve this. ->int0 you only need one line of code./ *nswer to Fxercise &
60
In the next section, we're going to move on to something called &onditional $ogic. !e'll use &onditional $ogic to complete the calculator. You will then be able to use it to divide, subtract, and multiply. "o make sure you save the work you've done so far;
61