Visual Basic 2010 Guide
Select...Case Statement

The Select...Case statement runs one of several groups of statements, depending on the value of an expression.

Example 1

Dim firstNum As Integer, secondNum As Integer
Dim choice As Integer
Dim answer As Integer
Console.Write("Enter the first number: ")
firstNum = Console.ReadLine()
Console.Write("Enter the second number: ")
secondNum = Console.ReadLine()
Console.Write("Enter 1 to add, 2 to subtract: ")
choice = Console.ReadLine()
Select Case choice
   Case 1
      answer = firstNum + secondNum
   Case 2
      answer = firstNum - secondNum
   Case Else
      answer = firstNum + secondNum
End Select

Console.WriteLine("The answer is {0}", answer)

Used like this, the Select Case statements are equivalent to the If statements we used before. The layout of the code would mean that, were there a large number of options, this way would be easier to read.

Example 2

The Select Case statement offers us yet another way to write the exam grade program,

Dim grade As String = ""
Dim score As Integer
Console.Write("Enter the score: ")
score = Console.ReadLine()
Select Case score
   Case Is >= 75
      grade = "A"
   Case 65 To 74
      grade = "B"
   Case 55 To 64
      grade = "C"
   Case Is < 55
      grade = "U"
End Select

Console.WriteLine("Your grade for the examination is {0} ", grade)

Again, readability of the code would be the main reason for choosing this method of selection - the last Case could be re-written as Case Else.

Having A Go

Feel free to use whichever of the selection techniques you find most useful for the following programs. A combination of the types of statement covered in this section will probably be required.

  1. Ask the user to input the number of a month. Display the name of the corresponding month.
  2. A year is a leap year if it is exactly divisible by 4 unless it is a century, in which case it must be divisible by 400 to be a leap year. Ask the user to enter a year and tell them whether or not it was a leap year. There is a built-in function, I know, but go with this.
  3. Ask the user for a month number and tell them the number of days in the month.
  4. Write a program that allows the user to enter a Module 1 examination score as an integer in the range 0 - 65. Convert the score into a grade using the boundaries specified below,

    A - 47, B - 42, C - 37, D - 33, E - 29
  5. Write a program which allows the user to input a number in the range 1 - 10. If the user has entered a number in the range, output the number in words to the screen. If they enter a number out of range, display an error message telling them off.