Visual Basic 2010 (Console) Guide
Validating Input

There are many things that can make your programs crash. This is different from the compiler errors you get when you have made a mistake in the code you write. Some of our programs rely on the user inputting the correct type of data. For example, when our programs expect an integer to be input, they crash if a string or if nothing is entered.

A well-designed program caters for this situation. One approach is to validate the input, inform the user if they have made an error and give them another chance. This usually means some sort of loop within the program logic.

Checking That Something Is Entered

The following program repeats a request for string data to be entered until something is typed at the prompt.

Console.Write("Enter your name: ")
Dim name As String = Console.ReadLine()
While name = ""
   Console.WriteLine("You need to enter your name.")
   Console.Write("Enter your name: ")
   name = Console.ReadLine()
End While
Console.WriteLine("Thank you for entering your name, {0}", name)

The same logic could be applied to a numeric value. Bear in mind that all information entered at the console comes as a string initially and you will need to perform conversions.

You can check if a string is numeric using the IsNumeric() function.

Having A Go

  1. Write a program that performs division only when two integers are entered, the second is smaller than the first, the second number is not a zero and both numbers are less than 100.
  2. Write a program that holds the user in a continual loop until they enter a specific word.