Sunday, February 20, 2011

Chapter 4 Summary

4.1
Code is executed sequentially, so it's order is significant to how the program executes. Using a decision structure, programs can execute different exceptions within the code. Conditionally executed is an action when a program executes different results when a user-driven decision is made. (Example: the book uses the "wear a coat" action if the user says it is cold outside. If the user clicks "no" instead, the "wear a coat" action is skipped over. These actions are only performed under a certain condition. These are known as "If...Then" statements.

4.2 The If...Then Statement
If...Then: causes other statements to execute only when an expression is true.
Looks something like:
"If expression Then
     statement
     (more statements may follow)
End If".
Basically tells the program that if the initial expression is true, then the statements between the If...Then and the End If are executed. Otherwise, they are skipped if the expression is false. Boolean expression is the term for the initial expression, as they can either be true or false.

Relational Operator: determines whether a specific relationship exists between two values.
Example: X>Y means is x greater than y?
The "=" operator in this case determines whether the operand on the left is equal to operand on the right.

See the test score example on page 210 to see the If...Then statement in use.

You can use math operators alongside relational operators, such as
"If intX+intY>20 Then
     lblMessage.Text="It is true!"
End If
Math operators are always performed before relational operators when they are in the same expression.

Relational operators can be used alongside function calls as well.

-Boolean variables can also be used as "flags", which signals when some condition exists in the program, either as "true" or "false".

4.3 If...Then...Else Statement
Looks like:
If condition Then
   statement
   more statements
Else
   statement
End If

Like the original If...Then statement, a Boolean expression is still evaluated. The "else" statement tells the program what to execute if the Boolean expression turns out to be false instead of true.

example:
If dblTemperature<40 Then
   lblMessage.Text="A little cold, isn't it?"
Else
   lblMessage.Text="Nice weather we'r having!"
End If

4.4 If...Then...ElseIf Statement
Example: When we decide to wear a jacket, we might think in terms of:
-If it is very cold, wear a heavy coat
-Else, if it is chilly, wear a light jacket
-Else, if it is windy, wear a windbreaker
-Else, if it is hot, wear no jacket

That type of decision making is the equivalent "If...Then...ElseIf" statements. Looks like:
If condition Then
   statement
ElseIf condition Then
   statement
(as many "ElseIf statements can be put here)
Else
   statement
End If

It's set-up like a chain, with the Else part of one statement being linked to the If part of another. All the "ElseIf" statements make up all the possibilities that need to be tried. See pg. 218 for the example.

4.5 Nested If Statements
Nested If Statement: is an If statement that appears inside another If statement.

Example: Loan Qualifier.
-The outermost "If" is testing the following the expression "If dblSalary>30,000 Then"
-If this is true, the nested if statement is executed, shown in bold.
If dblSalary>30000 Then
    If intYearsOnJob>2
        lblMessage.Text="The applicant qualifies."
    Else 
        lblMessage.Text="The applicant does not qualify."
    End If
Else
    If intYearsOnJob>5 Then
        lblMessage.Text="The applicant qualifies."
    Else
        lblMessage.Text="The applicant does not qualify."
    End If
End If
                                   
-However, if expression dblSalary>30000 isn't true, the Else part of the outermost If statement causes the nested If statement to execute, shown in bold.

Else
    If intYearsOnJob>5 Then
        lblMessage.Text="The applicant qualifies."
    Else
        lblMessage.Text="The applicant does not qualify."
    End If
End If

4.6 Logical Operators
Logical Operators: combine two or more Boolean expressions into a single expression.
Examples:
And: combines two expressions into one. Both must be true for the overall expression to be true.
-"AndAlso" can be used to achieve short-circuit evaluation (basically, if the first part of the "And" operator turns out to be false, Visual Studio can skip over the second part as the entire expression is false regardless).
Or: combines two expressions into one. One or both expressions must be true for the overall to be true.
-"OrElse" can be used to achieve short-circuit evaluation (in this case, if the first part is true, Visual Studio can now skip the second part as the entire expresssion is true regardless).
Xor: combines two into one. One expression (not both) must be true for the overall to be true. If both are true (or both flse), then overall is false.
Not: reverses the logical value of an expression: makes a true expression false and a false expression true.

Logical operators can be used to check numerical ranges. Example:
If intX>=20 And intX <=40 Then
   lblMessage.Text="The value is in the acceptable range."
End If

The If statement would only be true if the value is greater than 20 and less than 40.

An Or statement would be:
If intX<20 Or intX>40 Then
   lblMessage.Text= "The value is outside the acceptable range."
End If
This checks if th number is either less than 20 or greater than 40. If it is either one of those ranges, it's outside the acceptable range. Make sure to use the right operator, if you used And instead of Or, you'll get an error as no value exists that is both greater than 40 and less than 20.

You can use these statements together, such as:
If intX<0 and intY>100 Or intZ=50 Then
   statement
End If

4.7 Comparing, Testing and Working with Strings
Example:
strName1="Mary"
strName2="Mark"
If strName1=strName2 Then
   lblMessage.Text="The names are the same"
Else
   lblMessage.Text="The names are NOT the same"
End If

The "=" operator tests whether the strings are equal. "<>" ">" "<" "<=" ">=" can also all be used to test strings. You can use the greater than/less than operators because computers don't store characters as "A, B, C", they are stored as a numeric value. Because A comes before B, the numeric code for A is less than B, and so on.

You can test for whether a user has entered text into a text box by comparing the the text property to the predefined constant "String.Empty".

You can use the ToUpper/ToLower methods to change the case of the string. Example:
strLittleWord="Hello"
strBigWord=strLittleWord.ToUpper( )
This will turn "Hello" into "HELLO", and vice versa if .ToLower( ) is used instead.

IsNumeric Function
-Tests if a string contains a numeric value, true if it does, false if it doesn't.
"IsNumeric(StringExpression)"

Length Property
-Returns the number of characters in a string. Example:
"Herman" will be stored as the number 6, because there are 6 characters.
Dim strName As String="Herman"
Dim intNumChars As Integer
inNumChars=strName.Length

Can also determie length of a control's text property, using ControlName.Text.Length.

Trimming Spaces
You can trim leading/trailing spaces from strings using the StringExpression.TrimStart( ), StringExpression.TrimEnd( ), or StringExpression.Trim( ) methods.

You can trim spaces on a control's text property by using txtName.Text.Trim( ).

SubString Method
-Can be used to return a string within the string.
StringExpression.Substring(Start)
StringExpression.Substring(Start,Length)

Start refers to the character position (first character is 0, and so on).
The second method will give you exactly what you enter (the starting position and how many characters), and the first one will start at the position you give it and return all the characters that start from that position to the end of the string.

IndexOf Method
-Also first character position is 0 and so on.
-This searches for a character/string within a string.
Example:
Dim strName As String="Angelina Adams"
Dim intPosition As Integer
intPosition=strName.IndexOf("e")
This will return the integer "3" as "e" is in the third character position (remember first is 0)

Example:
Dim strName As String="Angelina Adams"
Dim intPosition As Integer
intPosition=strName.IndexOf("A", 1)
This will give the integer "9", as the 1 is telling the method to start at the first character position ("n") and to search for a capital A (a lowercase a and a capital A are different, keep this in mind). The "A" in Adams is in the 9th character position.

Example:
Dim strName As String="Angelina Adams"
Dim intPosition As Integer
intPosition=strName.IndexOf("A", 1, 7)
This will return the position of "-1", meaning the character position was not found. The 1 tells it where to start from in the string ("n" again) and to only search 7 character positions after the 1st character position. "A" is not found, so it returns -1.

4.8 More About Message Boxes
Here are different forms of message boxes.

MessageBox.Show(Message)
-This displays a message.
MessageBox.Show(Message, Caption)
-This displays a message, and "Caption" refers to what you want the title bar to display.
MessageBox.Show(Message, Caption, Buttons)
-This diplays a message, "Caption" is the title bar, and now you can choose what buttons you want using one of these:
-MessageBoxButtons.AbortRetryIgnore
-MessageBoxButtons.OK
-MessageBoxButtons.OKCancel
-MessageBoxButtons.RetryCancel
-MessageBoxButtons.YesNo
-MessageBoxButtons.YesNoCancel
These are pretty self-explanatory.
MessageBox.Show(Message, Caption, Buttons, Icon)
-This displays your message, your title bar caption, whatever button you selected, and you can choose the Icon(either an asterisk/"i" for information will be before your message, or an "x" or a "!" in a triangle, or a question mark) using:
-MessageBoxIcon.Asterisk
-MessageBoxIcon.Error
-MessageBoxIcon.Exclamation
-MessageBoxIcon.Question
Check page 243 for more.
MessageBox.Show(Message, Caption, Buttons, Icon, DefaultButton)
-Displays your message, displays your title bar caption, displays the buttons, displays the icon, and now chooses what button is the default (i.e. what button is clicked if the user presses "enter")
-MessageBoxDefaultButton.Button1
  -Selects the leftmost button.
-MessageBoxDefaultButton.Button2
   -Selects second button from the left.
-MessageBoxDefaultButton.Button3
   -Selects third button from the left.

Determining Which Button The User Clicked
Now that you have your message box, use If...Then...ElseIf statements to tell the program what to do in case of the button click. It's not an event handler for message boxes as Visual Studio returns specific values in case of a message box button click.

Example:
Dim intResult As Integer
intResult=MessageBox.Show("Do you wish to continue?", "Please Confirm", MessageBoxButtons.YesNo)

If intResult=Windows.Forms.DialogResult.Yes Then
   'Perform some action here
ElseIF intResult=Windows.Forms.DialogResult.No Then
   'Perform some action here
End If

See pg. 244 for more details.

4.9 Select Case Statement
Much like "If...Then...ElseIf" (this performs a series of tests and branches when one of the tests is true) statements, this tests the value of an expression only once and then uses that value to determine which set of statements to branch to.

Example:
Select Case CInt(txtInput.Text
   Case 1
      MessageBox.Show("Day 1 is Monday.")
   Case 2
      MessageBox.Show("Day 2 is Tuesday.")
   Case 3
      MessageBox.Show("Day 3 is Wednesday.")
   Case 4
      MessageBox.Show("Day 4 is Thursday.")
   Case 5
      MessageBox.Show("Day 5 is Friday.")
   Case 6
      MessageBox.Show("Day 6 is Saturday.")
   Case 7
      MessageBox.Show("Day 7 is Sunday.")
   Case Else
      MessageBox.Show("That value is invalid.")

Basically, this compares the integer of CInt(txtInput.Text) to whatever number case. If the integer is 3, it'll go through all the cases until it gets to case 3 and display the message box "Day 3 is Wednesday".

4.10 Input Validation
-The process of inspecting input values and determining whether they are valid.
-Now that we have If...Then statements, we can determine if a specific value can be converted to a specific data type before we try to convert it.

Methods:
-Integer.TryParse: Two arguments, string (argument 1) and integer variable (argument 2). Attempts to convert string to an integer. If successful, method returns true. If not, returns false.
-Double.TryParse: Tries to convert string to double. If successful, returns true. If not, returns false.
-Decimal.TryParse: ^
-Single.TryParse: ^
-Date.TryParse: ^

Etc.

4.11 Radion Buttons/Check Boxes
-All radio buttons inside a group box are members of the same group.
-All radio buttons on a form not inside a group box are members of the same group.
-Have a text property.
-Have a CheckedChanged event that is triggered when a user selects/deselects a radio button. Double-click on one to create the code.

Example:
If radChoice1.Checked=True Then
   MessageBox.Show("You selected Choice 1")
ElseIf radChoice2.Checked=True Then
   MessageBox.Show("You selected Choice 2")
ElseIf radChoice3.Checked=True Then
   MessageBox.Show("You selected Choice 3")
End If

You can use code to select a radio button, using an assignment statement to set the desired radion button's Checked property to "True":
radChoice1.Checked=True.

Check Box
-Text property for caption
-When it has focus, can be checked or unchecked using the spacebar
-Can use code to select or deselect a check box.
   -chkChoice4.Checked=True
-Have event handlers when checked/unchecked like radio buttons.

4.12 Building The Health Club Membership Fee Calculator Application
Look in the book, complete the example.

No comments:

Post a Comment