340 likes | 576 Views
Chapter 4: The Selection Process in Visual Basic. Learning Objectives. Understand the importance of the selection process in programming. Describe the various types of decisions that can be made in a computer program. Discuss the statement forms used in Visual Basic to make decisions.
E N D
Learning Objectives • Understand the importance of the selection process in programming. • Describe the various types of decisions that can be made in a computer program. • Discuss the statement forms used in Visual Basic to make decisions. • Understand the various comparison operators used in implementing decisions in Visual Basic. • Use the If-Then-Else, If-Then-ElseIf, and Case decision structures. • Use the list box control to select from a list of alternatives. • Work with complex comparison structures and nested decisions to handle more sophisticated selection processes. • Use the scroll bar to input integer values. • Use the Form_Load event to execute a procedure when a form is loaded. • Work with the debugging toolbar to find program errors.
The Selection Process • One of the key operations of a computer is to select between two or more alternatives to make a decision • Every decision involves a comparison between a variable and a constant, variable, or expression using logical operators • Decisions can involve two-alternatives or multiple alternatives
Types of Decisions • Decisions can involve two-alternatives or multiple alternatives • Two alternatives – use the IF-Then Else decision structure • Multiple alternatives – use the IF-Then-ElseIf or Select Case decision structure
The If-Then-Else Decision Structure • For two alternative decisions, the If-Then-Else decision structure should be used • In pseudocode, this is: If condition is True Then implement True alternative Else implement False alternative End Decision
If-Then-Else Payroll Example • In pseudocode, this is: If employee works > 40 hours Then employee pay= regular pay + OT pay Else employee pay= regular pay End Decision
Multiple Alternatives • For multiple alternatives, the general form in pseudocode is: Select one: Condition 1 is true; implement alternative 1 Condition 2 is true: implement alternative 2 Condition 3 is true; implement alternative 3 End Selection.
The Two Alternative Decision Structure • The If-Then-Else statement is: If condition is true Then statements for true alternative Else statements for false alternative End if • The If-Then condition test expression1 comparison operator test expression2 where comparison operator is one of these six operators: Equal to: = Less then: < Greater than: > Less than or equal to: <= Greater than or equal to: >= Not equal to: <>
VB Code Box 4-1If-Then-Else Decision to Compute Payroll ‘Declare variables and assign values Dim curPayRate as Currency, sngHours as Single Dim curPay as Currency curPayrate = CCur(txtPayRate.text) sngHours = CSng(txtHours.text) ‘Calculate Pay If Hours >= 40 then curPay = curPayRate * 40 + 1.5 * curPayRate * (Hours - 40) Else curPay = curPayRate * sngHours Endif ‘Format output text boxes as currency txtPay.text = Format(Pay,’’currency’’) txtPayRate.text=Format(txtPayRate.Text, ‘’currency’’)
One-Alternative Decision • If there is only a true alternative, then this is a special case of the two-alternative decision structure If condition is true Then true alternative is implemented End If • One-alternative decision can be combined with InputBox used to validate user input, e.g., to test that Customer Name textbox has something in it: If TxtCustName.Text = “” then txtCustName.Text = InputBox(“Enter Name and try again”) Exit Sub End if • Where the Exit Sub statement exits the event procedure • **** Know how InputBox statement is constucted!
VB Code Box 4-2Additional Code to Validate Input If txtCustName.Text = "" Then 'Check for customer name txtCustName.Text = InputBox("Enter name and try again.") Exit Sub 'No customer name entered End If If txtVideoName.Text = "" Then 'Check for video name txtVideoName.Text = InputBox("Enter video name and try again.") Exit Sub 'No video name entered End If
If-Then-ElseIf Decision Structure • One way to implement a multiple alternative decision structure is through the If-Then-ElseIf decision structure: (eliminates need for multiple End If statements) If condition1 True Then first set of statements ElseIf condition2 True Then second set of statements ElseIf condition3 True Then third set of statements Else last set of statements End if
Scroll Bar Control • Allows the user to enter a value without typing it in • Prefix is vsb for a vertical scroll bar or hsb for a horizontal scroll bar. • The key property is the Value property which responds to a Change Event as the scroll bar is moved. • Limits are set on the Value property by setting the Max and Min Properties., which are stored as Integer values
Scroll Bar Control (con’t) • Can also control the value property by setting the Small ChangeValue, which is the amount of the change when you click on the scroll bar arrows. • Can also control the Large Change Value which is the amount of the change when the interior of the scroll bar is clicked • Code is written as follows in the vsbAverage Change Event ( VB Code Box 4-3) • txtAverage.Text= Str(vsbAverage.Value) • Str converts the Integer value to the default data type of the textbox
VB Code Box 4-4If-Then-ElseIf for Determining a Letter Grade Dim intAverage as Integer, strLetterGrade as String intAverage = Cint(txtAverage.text) If intAverage >= 90 Then strLetterGrade = “A” ElseIf intAverage >= 80 Then strLetterGrade = “B” ElseIf intintAverage >= 70 Then strLetterGrade = “C” ElseIf intAverage >= 60 Then strLetterGrade = “D” Else strLetterGrade = “F” End if. txtLetter.Text = strLetterGrade
Using the Select Case Decision Structure for Multiple Alternatives • General form: Select Case expression (expression is variable you want to find, such as Average) Case Condition1 is true First set of statements Case Condition2 is true Second set of statements Case Condition3 is true Third set of statements Case Else Last set of statements End Select
Case Conditions • Conditions for Case statement can be in 3 forms: Test Condition Example Value or expression Case 91, 92, 93 Range of values Case 90 To 100 (first value must be less than the second value) Comparison condition Case Is > 89
VB Code Box 4-5Select Case to Determine LetterGrade Dim intAverage as Integer, strLetterGrade as String intAverage = CInt(txtAverage.text) Select Case intAverage Case Is >= 90 strLetterGrade = “A” Case Is >= 80 strLetterGrade = “B” Case Is >= 70 strLetterGrade = “C” Case Is >= 60 LetterGrade = “D” Case Else strLetterGrade = “F” End Select txtletter.txt=strLetterGrade
Using the List Box Control • The List box enables the user to select from a list of items. • lst is prefix for name • If a list box is not big enough to display all the possible entries a scroll bar is automatically added to it so the user can see all the items. • The List property of the list box can be set at design time or run time.
List Box Control (con’t) • If it is a short non changing list create it at design time by using the List Property • To move to the next item after adding an item be sure to press the CTRL+ Enter combination. • Items can only be added to the end of the list • The Text property of the list box is equal to the selected item. • When items are added to a list box a binary file with the .frx extension is created
VB Code Box 4-6Example of Using List Box Private Sub lstTypes_Click() Dim strVideoType as String, curPrice as Currency ‘lstTypes is list box strVideoType = lstTypes.Text Select Case strVideoType Case “Kids” curPrice = 0.99 Case “Regular” curPrice = 1.99 Case “Classic” curPrice = 2.99 End Select txtVideoType.text = Format(Price,”currency”) End Sub
VB Code Box 4-7Additional Code for cmdCalc strVideoType = lstTypes.Text If strVideoType = "" Then ‘Check for video type MsgBox "Select a video type and try again." Exit Sub ‘No video type selected End If _________________________________________ Insert above code immediately before the price assignment in cmdCalc event procedure. See VB Code box 4-8 for complete code for cmdCalc button
More Complex Decisions • Decisions within decisions are know as nested decisions • Interior decision must be an alternative of outer decision. In other words, any nested decision must be completely carried out within a True or False alternative. It is not possible to have a nested decision completed outside the alternative it appears • Indentation is used to show level of decision
More Complex Decisions (con’t) • Decisions that combine two or more test conditions using logical operators are known as compound decisions • And, Or, Not, and Xor are logical operators • Both conditions must be able to stand alone
Pseudocode for Nested Payroll Decision If PayStatus = Hourly Then If Hours > 40 Then Pay = PayRate * 40 + 1.5 * (Hours - 40) * PayRate * (Hours-40) Else Pay = PayRate * Hours End Decision Else Pay = PayRate * 40 End Decision
VB Code Box 4-9Example of Nested Decisions • Need to check if employee is hourly before checking for overtime: strPayType=lstPayType.Text If strPayType = “Hourly” Then ‘Hourly Can make overtime If sngHours > 40 Then ‘Pay status is hourly curPay = curPayRate * 40 + 1.5 * curPayRate * _ (sngHours-40) Else Pay = curPayRate * sngHours End if Else ‘Pay status is salaried curPay = curPayRate * 40 End if
Example of Compound Decisions • Using compound condition to test for average AND number of absences If intAverage >= 90 AND intAbsences <= 3 Then strLetterGrade = “A” ElseIf intAverage >= 80 AND intAbsences <= 5 then strLetterGrade = “B” etc. • In this case, if a student has an average of 93 and 4 absences, he/she will receive a grade of “B” because he/she has more than 3 absences.
Using the Form_Load Event • The Form_Load event occurs when the project is started and the form is loaded, not when you click or enter text in a text box.**** • Code from a command button can be cut (or copied) and then pasted into the form_load event
Using the Debug ToolBar • To view the Debug Toolbar, Select View|Toolbars and click the Debug checkbox • The Debug Toolbar Run Stop Step Into Step Out Immediate Window Quick Watch Break Toggle Step Over Locals Watch Window Call Stack Breakpoint Window
Debugging With the Immediate Window • By clicking the Immediate Window icon on the debug toolbar, you can then print the current value of a textbox or variable • Use the Print variable or textbox command to display its current value • This can enable you to find errors in the code