Section 5.3. Select Case Blocks


[Page 218 (continued)]

5.3. Select Case Blocks

A 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.
(This item is displayed on pages 218 - 219 in the print version)

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.

Object

Property

Setting

frmRace

Text

Horse Race

lblPosition

AutoSize

False

 

Text

Finishing position (1, 2, 3,...):

txtPosition

  

btnEvaluate

Text

Evaluate Position

txtOutcome

ReadOnly

True


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" 
[Page 219]
Case 4, 5 txtOutcome.Text = "You almost placed in the money." Case Else txtOutcome.Text = "Out of the money." End Select End Sub


[Run, type 2 into the text box, and press the button.]

Example 2.

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.]


[Page 220]

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.

Figure 5.4. Flowchart for a Select Case block.
(This item is displayed on page 221 in the print version)


Example 3.
(This item is displayed on pages 220 - 222 in the print version)

The following program uses several different types of value lists. With the response shown, the second action was selected.

Object

Property

Setting

frmRhyme

Text

One, Two, Buckle My Shoe

lblEnterNum

Text

Enter a number from 1 to 10:

txtNumber

  

btnInterpret

Text

Interpret Number

txtPhrase

ReadOnly

True


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) 
[Page 221]
Select Case num Case y - x, x txtPhrase.Text = "Buckle my shoe." Case Is <= 4 txtPhrase.Text = "Shut the door." Case x + y To x * y txtPhrase.Text = "Pick up sticks." Case 7, 8 txtPhrase.Text = "Lay them straight." Case Else txtPhrase.Text = "Start all over again." End Select End Sub



[Page 222]

[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.

Example 4.
(This item is displayed on pages 222 - 223 in the print version)

The following program has the string variable firstName as a selector.

Object

Property

Setting

frmQuiz

Text

Quiz

lblQuestion

AutoSize

False

 

Text

What was President Wilson's first name?

txtName

  

btnInterpret

Text

Interpret Answer

txtReply

ReadOnly

True


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



[Page 223]

[Run, type "Woodrow" into the text box, and press the button.]

Example 5.
(This item is displayed on pages 223 - 224 in the print version)

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.

Object

Property

Setting

frmAnalyze

Text

Analyze First Character of a String

lblEnter

Text

Enter a string:

txtString

  

btnAnalyze

Text

Analyze

txtResult

ReadOnly

True


 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



[Page 224]

[Run, type "Sunday" into the text box, and press the button.]

Example 6.
(This item is displayed on pages 224 - 225 in the print version)

The color of the beacon light atop Boston's John Hancock Building forecasts the weather according to the following rhyme:

Steady blue, clear view.
Flashing blue, clouds due.
Steady red, rain ahead.
Flashing red, snow instead.

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.

Object

Property

Setting

frmWeather

Text

Weather Beacon

lblColor

Text

Color of the light (B or R):

mtxtColor

Mask

L

lblMode

Text

Mode (S or F ):

mtxtMode

Mask

L

btnInterpret

Text

Interpret Beacon

txtForecast

ReadOnly

True


 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" 
[Page 225]
Case "FR" txtForecast.Text = "SNOW AHEAD" End Select End Sub


[Run, type "R" and "S" into the masked text boxes, and press the button.]

Example 7.
(This item is displayed on pages 225 - 226 in the print version)

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:

Object

Property

Setting

frmSeasons

Text

Seasons

lblSeason

Text

Season:

txtSeason

  

btnNumber

Text

Number of Days

txtNumDays

ReadOnly

True


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



[Page 226]

[Run, type "Summer" into the text box, and press the button.]

Comments

  1. 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.

  2. 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.

  3. 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.

  4. 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.

  5. 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.

Practice Problems 5.3

1.

Suppose the selector of a Select Case block is the numeric variable num. Determine whether each of the following Case clauses is valid.

  1. Case 1, 4, Is < 10

  2. Case Is < 5, Is >= 5

  3. Case num = 2

2.

Do the following two programs always produce the same output for a whole-number grade from 0 to 100?


[Page 227]

grade = CDbl(txtBox.Text) Select Case grade   Case Is >= 90      txtOutput.Text = "A"   Case Is >= 60      txtOutput.Text = "Pass"   Case Else      txtOutput.Text = "Fail" End Select


grade = CDbl(txtBox.Text) Select Case grade   Case Is >= 90     txtOutput.Text = "A"   Case 60 To 89     txtOutput.Text = "Pass"   Case 0 To 59     txtOutput.Text = "Fail" End Select



Exercises 5.3

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)")) 
[Page 228]
Select Case age
Case Is < 70 txtOutput.Text = "Cenozoic Era" Case Is < 225 txtOutput.Text = "Mesozoic Era" Case Is <= 600 txtOutput.Text = "Paleozoic Era" Case Else txtOutput.Text = "?" End Select End Sub


(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." 
[Page 229]
Case "JOHN MAUCHLY", "MAUCHLY", "J. PRESPER ECKERT", "ECKERT" txtOutput.Text = "He worked with the developer, "& _ "von Neumann, on the ENIAC." Case Else txtOutput.Text = "Nope." End Select End Sub


(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 &gt; word.Length       txtBox.Text = "Time keeps everything from happening at once."     Case Else       txtBox.Text = "The more things change, the less "&amp; _                    "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:")) 
[Page 230]
Select Case whatever Case Else txtOutput.Text = "Hi" End Select End Sub


(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." 
[Page 231]
Case word.Substring(0,1) = "P" txtOutput.Text = "The second word is PLURIBUS." Case Else txtOutput.Text = "The third word is UNUM." End Select End Sub


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"


[Page 232]

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.

Table 5.5. Cloudiness descriptors.
(This item is displayed on page 233 in the print version)

Percentage of Cloud Cover

Descriptor

030

clear

3170

partly cloudy

7199

cloudy

100

overcast


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.


[Page 233]

Table 5.6. Location of library books.

Call Numbers

Location

100 to 199

basement

200 to 500 and over 900

main floor

501 to 900 except 700 to 750

upper floor

700 to 750

archives


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:


    [Page 234]
  1. Who was the only living artist to have his work displayed in the Grand Gallery of the Louvre?

  2. Who said, "Computers are useless. They can only give you answers."?

  3. By what name is Pablo Blasio better known?

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.

Table 5.7. State flowers, nicknames, and mottoes.

State

Flower

Nickname

Motto

California

Golden Poppy

Golden State

Eureka

Indiana

Peony

Hoosier State

Crossroads of America

Mississippi

Magnolia

Magnolia State

By valor and arms

New York

Rose

Empire State

Ever upward


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.

Table 5.8. Physicians' abbreviations.

Abbreviation

Meaning

ac

before meals

ad lib

freely as needed

bid

twice daily

gtt

a drop

hs

at bedtime

qid

four times a day



[Page 235]
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."

Object

Property

Setting

frmExercise 37

  

lblNumber

Text

Number(13):

mtxtNumber

Mask

0

btnHumor

Text

&Humor

btnInsult

Text

&Insult

txtSentence

ReadOnly

True


Solutions to Practice Problems 5.3

1.

  1. Valid. These items are redundant because 1 and 4 are just special cases of Is < 10. However, this makes no difference in Visual Basic.

  2. Valid. These items are contradictory. However, Visual Basic looks at them one at a time until it finds an item containing the value of the selector. The action following this Case clause will always be carried out.

  3. Not valid. It should be Case 2.

2.

Yes. However, the program on the right is clearer and therefore preferable.




An Introduction to Programming Using Visual Basic 2005
Introduction to Programming Using Visual Basic 2005, An (6th Edition)
ISBN: 0130306541
EAN: 2147483647
Year: 2006
Pages: 164

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net