Download presentation
Presentation is loading. Please wait.
Published byKellie McDowell Modified over 8 years ago
1
Input Boxes, List Boxes, and Loops Chapter 5
2
2 Input Boxes Method for getting user’s attention to obtain input. InputBox() for obtaining input MessageBox() for displaying messages InputBox(“Prompt”,“Title Caption”, default) Prompt: onscreen message Title: string that displays in title bar Default: initial (optional) string value Returns value or string entered into input box. Stores return value or string into a variable.
3
Chapter 53 InputBox Example Click OK (or press Enter) to accept value and return it as a string to the function call. Click Cancel to return an empty string to the function call. Use assignment statement to store result.
4
Chapter 54 Potential Error No problem: If user types a number to return value to numeric variable. If user types a string to return string to string variable. If user clicks Cancel to return an empty string to a string variable. Problem: If user clicks Cancel to return an empty string to a numeric variable.
5
Chapter 55 Resulting Error Program can’t convert a zero-length string to a numeric data type, such as an integer.
6
Chapter 56 Problem Elimination Convert the results of the InputBox function to a value first.
7
Chapter 57 List Box Control (lst) Presents a list of choices. Enables user to select from the list. Highlights selected item(s). Occupies a specific amount of screen space. Prevents user from entering data. Displays scrollbar if not all items are displayed within designated control size.
8
Chapter 58 User gets to list box by tabbing to it, or clicking an item with the mouse, or using the access key and then pressing an arrow.
9
Chapter 59 List Box Design-Time Properties SelectionModeOne (Default) MultiSimple MultiExtended SortedFalse: Displays in original order True: Arranges in ascending order ItemsItems to display within list Create as property or within code (see next slide)
10
Chapter 510 Items Display in Order Entered
11
Chapter 511 SelectedIndex Property Stores selected item’s index value. The first item has an index value of 0. The second item has an index value of 1. If no item is selected, the list box SelectedIndex property is -1. If lstBeverages.SelectedIndex <> -1 Then strBeverage = lstBeverages.Items(lstBeverages.SelectedIndex) End If
12
Chapter 512 SelectedItem Stores index number of selected item in variable. Displays error message if nothing is selected.
13
Chapter 513 Default Selected Item Default No item selected Set default item ListBoxname.SelectedItem = Number
14
Chapter 514 Save Selected Item to Variable SelectedItem Property strItem = lstBeverages.SelectedItem
15
Chapter 515 Sorted Property Sorts text in order (by Unicode): AA Aa aA aa Requires leading zeros to properly sort numbers. 15 sorts before 5 05 sorts before 15
16
Chapter 516 Practice Example 1 Create list box named lstBeverages. Use Items property to enter items: Pepsi Diet Pepsi Wild Cherry Pepsi Pepsi One Run program and note order. Set Sorted to True & run program again.
17
Chapter 517 Adding Items Method Add Items (use to populate list box instead of using Items property or to add item stored in variable to the list) lstBeverages.Items.Add("Vanilla Coke") Adds item to end of list (no index specified) Insert Items in particular location lstBeverages.Items.Insert(“7-Up", 0) Adds item to beginning of list Rest of items move down 1 Specify Sort property (True) to automatically arrange added items.
18
Chapter 518 Remove Items ListBox.Items.Remove(Item) lstBeverages.Items.Remove(“7-Up”) Removes specific item. lstBeverages.Items.RemoveAt(4) Removes item with 4 th index number. ListBox.Items.Clear() Erases all items in the Items property.
19
Chapter 519 Structures Sequential Conditional (If, Select Case) Repetition (loops)
20
Chapter 520 Loop Loop—Structure that executes a group of statements repeatedly. The structure controls number of loops. Looping—Process of repeating a series of instructions. Iteration—A single execution of the statements in the loop. Infinite Loop—A loop that executes forever (bad programming—you need a way to get out of the loop); if happens, press Ctrl+Break. Types: Do While Do Until For…Next
21
Chapter 521 Do…Loop Process Executes the statement block repeatedly until a specified condition occurs. Useful When programmer does not know how many times the statements need to be executed. Variations Do While Loop (pretest) Do Loop While (posttest)
22
Chapter 522 Do While…Loop Syntax Do While condition statement block Loop Do marks top of loop. While is the termination condition: at top of the loop. Condition is a logical expression. Loop causes execution to go back to the top of the loop—at the Do statement.
23
Chapter 523 Do While Pretest Do While Loop Complete False Loop Condition Statements In Loop True Do While condition statement block Loop
24
Chapter 524 Do While Process Tests condition (represented by diamond in flowchart), thus name conditionally executed. If condition is true, process statement block. Then go back to test the condition again. If condition is false, skip statement block and go to the code after the Loop statement. Note: May never process if condition is false to start. We’ll look at setting up situation before entering loop.
25
Chapter 525 Example X VariableIterationMessage Box (before loop)N/A 1 2 3 4 5 6
26
Chapter 526 Loop Body Considerations One or more statements must eventually cause the condition to become false (to prevent infinite loop). The order of statements is critical—the statements affect the result of the loop. Previous example first message: 1 Reverse 2 statements X += 1 MessageBox.Show Reverse statements first message: 0 The loop can terminate immediately if condition is false—make sure loop does not contain code that is needed regardless of condition.
27
Chapter 527 Counter Variable Variable that regularly increments or decrements during each loop iteration. Increments Add 1 (or another value) to its value X = X + 1orX += 1 Decrements Subtract 1 (or another value) to its value X = X – 1orX -= 1 Proper initialization is critical. Without it, the loop may iterate 1 time too many or 1 time less than it should.
28
Chapter 528 Breakpoints to See Variable Contents Click Margin Indicator where you want to set the breakpoint. Choose Debug | Step Into. Turn on Autos window.
29
Chapter 529 Variable Contents Yellow current code Mouse over to see variable contents Click and choose Autos Current X variable value before statement executed
30
Chapter 530 Current X variable value after statement executed Mouse over to see variable value
31
Chapter 531 Pretest vs. Posttest Pretest Tests condition at the beginning of the block. If condition is true, complete at least one iteration. If condition is false, no iteration completed. Do While…Loop Posttest Tests condition at the end of the block. Completes at least one iteration. Do…Loop While
32
Chapter 532 Do…Loop While Process Executes the statement block while the condition is true. Terminates when condition becomes false. Processes at least once (even when false) because the condition is tested after the first iteration. Useful To ensure at least one iteration of the statement block (which is posttest).
33
Chapter 533 Do…Loop While Syntax Do statement block Loop While condition Do marks top of loop. Loop While tests the condition posttest and causes a new iteration if the condition is true. Condition is a logical expression.
34
Chapter 534 Do…While Loop Posttest Do Loop Complete False Loop While Condition Statements In Loop True
35
Chapter 535 Do…Loop While Process Processes statement block first time. Tests condition in the Loop While line. If condition is true, then loops back to Do statement and starts another iteration. If condition is false, then goes to next line of code after the Loop While statement. Note: Always completes one iteration regardless of condition.
36
Chapter 536 Example 7.5 (from Burrows) Type Randomize() in the Form Load event.
37
Chapter 537 Accumulator Variable Sum of #s accumulated with each iteration. Accumulator Counter increments
38
Chapter 538 Let User Control Loop User decides how many times the loop iterates. Program enables user to provide input, which is used for counter. Study code in Tutorial 5-5 (pp. 286-287).
39
Chapter 539 Checkpoint Go through checkpoints on pp. 287-288.
40
Chapter 540 Do Until…Loop Similar to Do While…Loop except: Different keywords Do Until…Loop condition executes when condition is false, whereas Do While…Loop executes when condition is true. Do Until…Loop exits when condition is true; Do While…Loop exits when condition is false.
41
Chapter 541 Do Until…Loop Pretest Do Until Loop Complete Loop Condition Statements In Loop False Do Until condition statement block Loop True
42
Chapter 542 Do Until…Loop Evaluations condition in the Do Until statement. If the condition is false, VB executes statement block. Then evaluates condition again. If the condition is true, VB skips statement block; ends loop.
43
Chapter 543 Do…Loop Until Similar to Do…Loop While except: Evaluation of condition for True/False is reversed.
44
Chapter 544 Do…Loop Until Posttest Do Loop Complete True Loop Until Condition Statements In Loop False Ensures one iteration of the statement block. Does statement block until the condition is true; then it exits the loop.
45
Chapter 545 Do Until Loop Example Create a program to average test scores. Use only labels and buttons. When the user clicks the Average button, the program prompts the user to enter the # of test scores. Use Do Until loop to display Input Boxes to get that number of scores.
46
Chapter 546 Do…Loop Until Example Create a program that gets a # from the user. Add that number to the same variable (accumulator). Continue looping until the accumulator sum is 10. Display # of #s entered and their sum
47
Chapter 547 Exercise 7.5 Burrows
48
Chapter 548 Initialization & Termination Errors often caused because loop iterates 1 too many times or 1 less time than desired. Error stems from the initial value of variable involved in the loop.
49
Chapter 549 Potential Sources of Problem Initialization is off by one. Loop condition causes problem. See if = corrects error. Statements in loop are out of order.
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.