5.3. Select Case BlocksA Select Case block is an efficient decision-making structure that simplifies choosing among several actions. It avoids complex If constructs. If blocks make decisions based on the truth value of a condition; Select Case choices are determined by the value of an expression called a selector. Each of the possible actions is preceded by a clause of the form Case valueList where valueList itemizes the values of the selector for which the action should be taken. Example 1. |
The following program converts the finishing position in a horse race into a descriptive phrase. After the variable position is assigned a value from txtPosition, Visual Basic searches for the first Case clause whose value list contains that value and executes the succeeding statement. If the value of position is greater than 5, then the statement following Case Else is executed.
Private Sub btnEvaluate_Click(...) Handles btnEvaluate.Click Dim position As Integer 'selector position = CInt(txtPosition.Text) Select Case position Case 1 txtOutcome.Text = "Win" Case 2 txtOutcome.Text = "Place" Case 3 txtOutcome.Text = "Show" [Run, type 2 into the text box, and press the button.]
|
In the following variation of Example 1, the value lists specify ranges of values. The first value list provides another way to stipulate the numbers 1, 2, and 3. The second value list covers all numbers from 4 on. Private Sub btnEvaluate_Click(...) Handles btnEvaluate.Click 'Describe finishing positions in a horse race Dim position As Integer position = CInt(txtPosition.Text) Select Case position Case 1 To 3 txtOutcome.Text = "In the money. Congratulations." Case Is >= 4 txtOutcome.Text = "Not in the money." End Select End Sub [Run, type 2 into the text box, and press the button.]
|
A typical form of the Select Case block is
Select Case selector Case valueList1 action1 Case valueList2 action2 Case Else action of last resort End Select
where Case Else (and its action) is optional, and each value list contains one or more of the following types of items:
1. | a literal; |
2. | a variable; |
3. | an expression; |
4. | an inequality sign preceded by Is and followed by a literal, variable, or expression; |
5. | a range expressed in the form a To b, where a and b are literals, variables, or expressions. |
Different items appearing in the same list must be separated by commas. Each action consists of one or more statements. After the selector is evaluated, Visual Basic looks for the first value-list item including the value of the selector and carries out its associated action. (If the value of the selector appears in two different value lists, only the action associated with the first value list will be carried out.) If the value of the selector does not appear in any of the value lists and there is no Case Else clause, execution of the program will continue with the statement following the Select Case block.
Figure 5.4 (on the next page) contains the flowchart for a Select Case block. The pseudocode for a Select Case block is the same as for the equivalent If block.
The following program uses several different types of value lists. With the response shown, the second action was selected.
Private Sub btnInterpret_Click(...) Handles btnInterpret.Click 'One, Two, Buckle My Shoe Dim x As Integer = 2, y As Integer = 3 Dim num As Integer num = CInt(txtNumber.Text) [Run, type 4 into the text box, and press the button.]
|
In each of the three preceding examples, the selector was a numeric variable; however, the selector also can be a string variable or an expression.
The following program has the string variable firstName as a selector.
Private Sub btnInterpret_Click(...) Handles btnInterpret.Click 'Quiz Dim firstName As String firstName = txtName.Text.ToUpper Select Case firstName Case "THOMAS" txtReply.Text = "Correct." Case "WOODROW" txtReply.Text = "Sorry, his full name was " & _ "Thomas Woodrow Wilson." Case "PRESIDENT" txtReply.Text = "Are you for real?" Case Else txtReply.Text = "Nice try, but no cigar." End Select End Sub [Run, type "Woodrow" into the text box, and press the button.]
|
The following program has the string selector anyString.Substring (0, 1). In the sample run, only the first action was carried out, even though the value of the selector was in both of the first two value lists. Visual Basic stops looking as soon as it finds the value of the selector.
Private Sub btnAnalyze_Click(...) Handles btnAnalyze.Click 'Analyze the first character of a string Dim anyString As String anyString = txtString.Text.ToUpper Select Case anyString.Substring(0, 1) Case "S", "Z" txtResult.Text = "The string begins with a sibilant." Case "A" To "Z" txtResult.Text = "The string begins with a nonsibilant." Case "0" To "9" txtResult.Text = "The string begins with a digit." Case Is < "0" txtResult.Text = "The string begins with a character of " & _ "ANSI value less than 48." Case Else txtResult.Text = "The string begins with : ; < = > " & _ " ? @ [ \ ] ^ _ or ' . " End Select End Sub [Run, type "Sunday" into the text box, and press the button.]
|
The color of the beacon light atop Boston's John Hancock Building forecasts the weather according to the following rhyme: Steady blue, clear view. The following program requests a color (Blue or Red) and a mode (Steady or Flashing) as input and displays the weather forecast. The program contains a Select Case block with a string expression as selector.
Private Sub btnInterpret_Click(...) Handles btnInterpret.Click 'Interpret a weather beacon Dim color, mode As String color = mtxtColor.Text mode = mtxtMode.Text Select Case mode.ToUpper & color.ToUpper Case "SB" txtForecast.Text = "CLEAR VIEW" Case "FB" txtForecast.Text = "CLOUDS DUE" Case "SR" txtForecast.Text = "RAIN AHEAD" [Run, type "R" and "S" into the masked text boxes, and press the button.]
|
Select Case is useful in defining functions that are not determined by a formula. The following program assumes that the current year is not a leap year:
Private Sub btnNumber_Click(...) Handles btnNumber.Click 'Determine the number of days in a season Dim season As String season = txtSeason.Text txtNumDays.Text = season & " has " & NumDays(season) & " days." End Sub Function NumDays(ByVal season As String) As Integer 'Look up the number of days in a given season Select Case season.ToUpper Case "WINTER" Return 87 Case "SPRING" Return 92 Case "SUMMER", "AUTUMN", "FALL" Return 93 End Select End Function [Run, type "Summer" into the text box, and press the button.]
|
In a Case clause of the form Case b To c, the value of b should be less than or equal to the value of c. Otherwise, the clause is meaningless.
If the word Is, which should precede an inequality sign in a value list, is accidentally omitted, the editor will automatically insert it when checking the line.
The items in the value list must evaluate to a literal of the same type as the selector. For instance, if the selector evaluated to a string value, as in
Dim firstName As String firstName = txtBox.Text Select Case firstName
then the clause
Case firstName.Length
would be meaningless.
Variables are rarely declared inside an If ... Then block or a Select Case block. If so, such a variable has block-level scope; that is, the variable cannot be referred to by code outside of the block.
In Appendix D, the section "Stepping through Programs Containing Selection Structures: Chapter 5" uses the Visual Basic debugging tools to trace the flow through a Select Case block.
1. | Suppose the selector of a Select Case block is the numeric variable num. Determine whether each of the following Case clauses is valid.
| ||
2. | Do the following two programs always produce the same output for a whole-number grade from 0 to 100?
|
In Exercises 1 through 8, for each of the responses shown in the parentheses, determine the output displayed in the text box when the button is clicked.
1. | Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim age, price As Double age = CDbl(InputBox("What is your age?")) Select Case age Case Is < 6 price = 0 Case 6 To 17 price = 3.75 Case Is >= 17 price = 5 End Select txtOutput.Text = "The price is "& FormatCurrency(price) End Sub (8.5, 17) |
2. | Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim n As Double n = CDbl(InputBox("Enter a number from 5 to 12")) Select Case n Case 5 txtOutput.Text = "case 1" Case 5 To 7 txtOutput.Text = "case 2" Case 7 To 12 txtOutput.Text = "case 3" End Select End Sub (7, 5, 11.2) |
3. | Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim age As Integer age = CDbl(InputBox("Enter age (in millions of years)")) (100, 600, 700) |
4. | Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim yearENIAC As Integer AskQuestion(yearENIAC) ProcessAnswer(yearENIAC) End Sub Sub AskQuestion(ByRef yearENIAC As Integer) 'Ask question and obtain answer Dim message As String message = "In what year was the ENIAC computer completed?" yearENIAC = CInt(InputBox(message)) End Sub Sub ProcessAnswer(ByVal yearENIAC As Integer) 'Respond to answer Select Case yearENIAC Case 1945 txtOutput.Text = "Correct." Case 1943 To 1947 txtOutput.Text = "Close, 1945." Case Is < 1943 txtOutput.Text = "Sorry, 1945. Work on the ENIAC "& _ "began in June 1943." Case Is > 1947 txtOutput.Text = "No, 1945. By then IBM had built "& _ "a stored-program computer." End Select End Sub (1940, 1945, 1950) |
5. | Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim name As String name = InputBox("Who developed the stored-program concept?") Select Case name.ToUpper Case "JOHN VON NEUMANN", "VON NEUMANN" txtOutput.Text = "Correct." (Grace Hopper, Eckert, John von Neumann) |
6. | Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim message As String, a, b, c As Double message = "Analyzing solutions to the quadratic equation " message &= "AX^2 + BX + C = 0. Enter the value for " a = CDbl(InputBox(message & "A")) b = CDbl(InputBox(message & "B")) c = CDbl(InputBox(message & "C")) Select Case (b ^ 2) - (4 * a * c) Case Is < 0 txtOutput.Text = "The equation has no real solutions." Case 0 txtOutput.Text = "The equation has exactly one solution." Case Is > 0 txtOutput.Text = "The equation has two solutions." End Select End Sub (1,2,3; 1,5,1; 1,2,1) |
7. | Private Sub btnDisplay_Click(...) Handles btnDisplay.Click 'State a quotation Dim num1, num2 As Double Dim word As String = "hello" num1 = 3 num2 = CDbl(InputBox("Enter a number")) Select Case (2 * num2 - 1) Case num1 * num1 txtBox.Text = "Less is more." Case Is > word.Length txtBox.Text = "Time keeps everything from happening at once." Case Else txtBox.Text = "The more things change, the less "& _ "they remain the same." End Select End Sub (2, 5, 6) |
8. | Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim whatever As Double whatever = CDbl(InputBox("Enter a number:")) (7,-1) In Exercises 9 through 16, identify the errors. |
9. | Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim num As Double = 2 Select Case num txtOutput.Text = "Two" End Select End Sub |
10. | Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim num1 As Double = 5 Dim num2 As Double = 2 Select Case num1 Case 3 <= num1 <= 10 txtOutput.Text = "between 3 and 10." Case num2 To 5; 4 txtOutput.Text = "near 5." End Select End Sub |
11. | Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim a As String a = InputBox("What is your name?") Select Case a Case a = "Bob" txtOutput.Text = "Hi, Bob." Case Else End Select End Sub |
12. | Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim word As String = "hello" Select Case word.Substring(0,1) Case h txtOutput.Text = "begins with h." End Select End Sub |
13. | Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim word As String word = InputBox("Enter a word from the United States motto.") Select Case word.ToUpper Case "E" txtOutput.Text = "This is the first word of the motto." |
14. | Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim num As Double = 5 Select Case num Case 5, Is <> 5 txtOutput.Text = "five" Case Is > 5 txtOutput.Text = "greater than five" End Sub |
15. | Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim fruit As String = "Peach" Select Case fruit.ToUpper Case Is >= "Peach" txtOutput.Text = "Georgia" Case "ORANGE To PEACH" txtOutput.Text = "Ok" End Select End Sub |
16. | Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim purchase As Double purchase = CDbl(InputBox("Quantity purchased?")) Select Case purchase Case purchase < 10000 txtOutput.Text = "Five dollars per item." Case Is 10000 To 30000 txtOutput.Text = "Four dollars per item." Case Is > 30000 txtOutput.Text = "Three dollars per item." End Select End Sub |
In Exercises 17 through 22, suppose the selector of a Select Case block, word, evaluates to a String value. Determine whether the Case clause is valid.
17. | Case "un" & "til" |
18. | Case "hello", Is < "goodbye" |
19. | Case 0 To 9 |
20. | Case word <> "No" |
21. | Case "abc".Substring(0, 1) |
22. | Case Is <> "No" |
In Exercises 23 through 26, rewrite the code using a Select Case block.
23. | If a = 1 Then txtOutput.Text = "one" Else If a > 5 Then txtOutput.Text = "two" End If End If | |||||||||||||||||||||
24. | If a = 1 Then lstOutput.Items.Add("lambs") End If If ((a <= 3) And (a < 4)) Then lstOutput.Items.Add("eat") End If If ((a = 5) Or (a > 7)) Then lstOutput.Items.Add("ivy") End If | |||||||||||||||||||||
25. | If a < 5 Then If a = 2 Then txtOutput.Text = "yes" Else txtOutput.Text = "no" End If Else If a = 2 Then txtOutput.Text = "maybe" End If End If | |||||||||||||||||||||
26. | If a = 3 Then a = 1 End If If a = 2 Then a = 3 End If If a = 1 Then a = 2 End If | |||||||||||||||||||||
27. | Table 5.5 gives the terms used by the National Weather Service to describe the degree of cloudiness. Write a program that requests the percentage of cloud cover as input and then displays the appropriate descriptor.
| |||||||||||||||||||||
28. | Table 5.6 shows the location of books in the library stacks according to their call numbers. Write a program that requests the call number of a book as input and displays the location of the book.
| |||||||||||||||||||||
29. | Write a program that requests a month of the year and then gives the number of days in the month. If the month is February, the user should be asked whether the current year is a leap year. | |||||||||||||||||||||
30. | Figure 5.5 shows some geometric shapes and formulas for their areas. Write a program that requests the user to select one of the shapes, requests the appropriate lengths, and then gives the area of the figure. The areas should be computed by Function procedures. Figure 5.5. Areas of geometric shapes.
| |||||||||||||||||||||
31. | Write a program that requests an exam score and assigns a letter grade with the scale 90100 (A), 8089 (B), 7079 (C), 6069 (D), 059 (F). The computation should be carried out in a Function procedure. (Test the program with the grades 84, 100, and 57.) | |||||||||||||||||||||
32. | Computerized quiz show. Write a program that asks the contestant to select one of the numbers 1, 2, or 3 and then calls a Sub procedure that asks the question and requests the answer. The program should then tell the contestant if the answer is correct. Use the following three questions:
Note: These questions have the same answer, Pablo Picasso. | |||||||||||||||||||||
33. | IRS informants are paid cash awards based on the value of the money recovered. If the information was specific enough to lead to a recovery, the informant receives 10 percent of the first $75,000, 5 percent of the next $25,000, and 1 percent of the remainder, up to a maximum award of $50,000. Write a program that requests the amount of the recovery as input and displays the award. (Test the program on the amounts $10,000, $125,000, and $10,000,000.)(Note:The source of this formula is The Book of Inside Information, Boardroom Books, 1993.) | |||||||||||||||||||||
34. | Table 5.7 contains information on several states. Write a program that requests a state and category (flower, motto, and nickname) as input and displays the requested information. If the state or category requested is not in the table, the program should so inform the user.
| |||||||||||||||||||||
35. | Write a program that, given the last name of one of the five most recent presidents, displays his state and a colorful fact about him. (Hint: The program might need to request further information.) Note: Carter: Georgia; The only soft drink served in the Carter White House was Coca-Cola. Reagan: California; His Secret Service code name was Rawhide. George H. W. Bush: Texas; He was the third left-handed president. Clinton: Arkansas; In college he did a good imitation of Elvis Presley. George W. Bush: Texas; He once owned the Texas Rangers baseball team. | |||||||||||||||||||||
36. | Table 5.8 contains the meanings of some abbreviations doctors often use for prescriptions. Write a program that requests an abbreviation and gives its meaning. The user should be informed if the meaning is not in the table.
| |||||||||||||||||||||
37. | The user enters a number into a masked text box and then clicks on the appropriate button to have either one of three pieces of humor or one of three insults displayed in a text box below the buttons. Place the humor and insults in Function procedures, with Select Case statements in each to return the appropriate phrase. Also, if the number entered is not between 1 and 3, the masked text box should be cleared. Note: Some possible bits of humor are "I can resist everything except temptation," "I just heard from Bill Bailey. He's not coming home," and "I have enough money to last the rest of my life, unless I buy something." Some possible insults are "How much would you charge to haunt a house?" "I bet you have no more friends than an alarm clock," and "When your IQ rises to 30, sell."
|
1. |
|
2. | Yes. However, the program on the right is clearer and therefore preferable. |