Introduction to 2A VISUAL BASIC

 edition

Copyright © HKTA Tang Hin Memorial Secondary School 2016 Table of Contents

.C .h .a .p .t e. r. 1. . . . . S. t.r .i n. g. .O . p. e. r.a .t i.o .n .s ...... 3...... 1. ..1 . . . . .S .t r. i.n .g . f.u . n. c. t.i o. n. .s ...... 7 ...... 1. ..2 . . . . .D .e .t .a .i l.s . o. f. s. t.r .i n. g. .f .u .n .c .t i.o . n. s...... 9 ...... 1. ..3 . . . . .C .o .m . .p .a .r i.s .o .n . o. .f .s .t r.i .n .g .s ...... 1 .6 ...... 1. ..4 . . . . .S .t r. i.n .g . m. .a .t .c h. .i n. g...... 1 .8 ...... E. x. e. r. c. i.s e. .1 ...... 2 .2 ...... C .h .a .p .t e. r. 2. . . . . V. a. l.i d. a. t. i.o .n . o. f. I.n .p .u .t ...... 2. 4...... 2. ..1 . . . . .R .a .n .g .e . c. h. e. c. k...... 2 .5 ...... 2. ..2 . . . . .F .o .r m. . a. t. c. h. e. c. k. .w . i.t h. .T . r.y .P .a .r .s e...... 2 .6 ...... E. x. e. r. c. i.s e. .2 ...... 2 .9 ...... G .l o. s. s.a .r .y ...... 3. 0...... String Operations 3 Chapter 1 String Operations

In this chapter, we learn about strings and text manipulation in VB.NET. Strings and characters

Text is stored in computer programs in the form of strings. A string is a sequence of characters. There are different types of characters, such as letters, digits, punctuation marks, symbols, white spaces, and control characters. How is text stored in computers?

Unlike humans, computers do not recognise text by its image or sound. Instead, text is converted into numbers, and computers store the numbers instead. A scheme that maps characters into numbers is called a character set. We also have a concept of , which tells how text in a particular character set is stored in memory. The concept of character encoding is particularly important for , which has different character encodings for the same character set. For other character sets, we can simply use these two terms interchangeably. A few common character sets are introduced below: ASCII

ASCII, the American Standard Code for Information Interchange, is an old character set which is still significant nowadays. ASCII is still significant because most character sets (including , GBK, and Unicode) are backwards compatible with ASCII. We use the term compatible because these character sets contain an exact copy of the US-ASCII character set. ASCII consists of 128 characters, and each character is assigned a code point. However, only code points 32 to 126 are “printable”, i.e. used for text. The rest of the characters are called control characters. 4 Introduction to Visual Basic (Part 2)

Here is the list of ASCII printable characters. You are supposed to remember the code point of letters and digits, but not the special symbols. Table 1. ASCII table (printable characters only) 32 48 64 80 96 112 +0 (sp) 0 @ P ` p +1 ! 1 A Q a q +2 " 2 B R b r +3 # 3 C S c s +4 $ 4 D T d t +5 % 5 E U e u +6 & 6 F V f v +7 ' 7 G W g w +8 ( 8 H X h x +9 ) 9 I Y i y +10 * : J Z j z +11 + ; K [ k { +12 , < L \ l | +13 - = M ] m } +14 . > N ^ n ~ +15 / ? O _ o

For the control characters, only CR (13) and LF (10) are significant in VB.NET. In Windows, the character sequence CR + LF moves the cursor to the next line. In VB.NET, this sequence can be referred as the constant vbCrLf . String Operations 5 Big5 and GBK

In the past, different character sets were used to store text in different languages. We used Big5 for traditional Chinese and GBK for simplified Chinese. Unfortunately, with the exception of ASCII, we cannot mix text with different character sets together. Worse still, text at those times was often communicated without specifying a character set, or even specifying a wrong character set. When this happened, the text cannot be read unless the actual character set is selected. If a wrong character set is used to read text, the text appears garbled. See the figure below for an example of selecting a wrong character set. This continues to happen for some web sites today, like the one in the figure.

Figure 1. (Left) A web page rendered with a wrong character set. (Right) The same web page after selecting the right character set. Source: https://market.cloud.edu.tw/content/primary/math/ch_dc/tea_page/pauran/basic.htm 6 Introduction to Visual Basic (Part 2) Unicode

Finally, Unicode is made to encode text in different languages simultaneously with a single system. There are three mainstream character encodings in Unicode, namely UTF-8, UTF-16, and UTF-32. Here is a comparison of the character encodings:

Character encoding Size of code unit (bytes) Size of a character (bytes) ASCII 1 1 Big5 1 1 or 2 GBK 1 1 or 2 UTF-8 1 1, 2, 3 or 4 UTF-16 2 2 or 4 UTF-32 4 4

Strings in .NET platform

Strings in .NET platform are encoded in UTF-16. In UTF-16, characters with Unicode code point 65535 or below are encoded with one code unit (2 bytes), and others are encoded with two code units (4 bytes). If a character is encoded in two code units, then it behaves like two separate characters in VB.NET. In these cases, string functions related to characters, the length of string and position of characters do not work properly. Unfortunately, these special characters include Chinese names and Emojis, which are quite commonly used. See http://www.unicode.org/charts/PDF/U20000.pdf to see a list of Chinese characters and http://unicode.org/emoji/charts/full-emoji-list.html for the list of Emojis. If your application handles text in other languages, then the situation is even more complex because of combining diacritical marks. The concepts involved are too advanced to discuss here.

 a a a a ( 12 ) 123 String functions 7 1.1 String functions

A few essential string functions are listed here. First, we learn a function that returns the length of the string:

Function Syntax and Meaning Example Result

Len Len(str) Len("Very good!") 10 Returns the length of the string, Len("鄧顯") 2 i.e. its number of characters. Next, a few functions that extract a part of a string are introduced:

Function Syntax and Meaning Example Result

Left Left(str, Length) Left("Wonder", 3) "Won" Returns a specified number of characters from the left of the string.

Right Right(str, Length) Right("Wonder", 2) "er" Returns a specified number of characters from the right of the string.

Mid Mid(str, Start) Mid("Block", 2, 3) "loc" Mid(str, Start, Length) Mid("clever", 3) "ever" Returns a specified number of characters from a string. If Length is not supplied, all characters from position Start is returned.

Trim Trim(str) Trim(" I win! ") "I win!” Removes white space characters at the beginning and at the end of a string. Then, we learn functions that do transformations on a string:

Function Syntax and Meaning Example Result

UCase UCase(str) UCase("good!") "GOOD!" Converts a string to upper case.

LCase LCase(str) LCase("sMaRt") "smart" Converts a string to lower case. 8 Introduction to Visual Basic (Part 2)

Next, we have functions that convert characters to and from their Unicode code point:

Function Syntax and Meaning Example Result

AscW AscW(str) AscW("A") 65 Returns the Unicode code point of the first character of the string.

ChrW ChrW(charCode) ChrW(65) "A" Returns the character with the given Unicode code point. Finally, we have functions that search for a string within another string:

Function Syntax and Meaning Example Result

String.StartsWith [str1].StartsWith(str2) "example".StartsWith("ex") True Returns True if str1 starts with "example".StartsWith("ple") False str2, False otherwise.

String.EndsWith [str1].EndsWith(str2) "example".EndsWith("ex") False Returns True if str1 ends with "example".EndsWith("ple") True str2, False otherwise.

InStr InStr(Start, Str1, Str2) InStr("aabc", "ab") 2 InStr(Str1, Str2) InStr("abc", "d") 0 Returns an integer which is the start InStr(1,"rear","r") 1 position of the first occurrence of InStr(2,"rear","r") 4 Str2 within Str1. Returns zero if Str2 is not found. Details of string functions 9 1.2 Details of string functions

In this section, we discuss the details of functions Len , Left , Right , Mid , Trim , AscW and ChrW . String matching will be discussed in another section. In some string functions, there are boundary cases that need to be discussed. A boundary case is a special case that one or more input is at or just beyond its maximum or minimum limits. For example, if the valid mark is from 0 to 100, we consider -1, -0.1, 0, 100, 100.1 and 101 as the boundary cases.

If you intend to write a real application, use string functions that work  properly in Unicode. In the functions discussed here, only UCase and LCase work properly.

Len function

Len function means to return the number of characters in the string. An empty string ( "" ) has a length of 0. Here is an example:

Dim TestString As String = "Hello World" Dim TestLength As Integer = Len(TestString) ' Returns 11. 10 Introduction to Visual Basic (Part 2) Left and Right functions

Left and Right extract the specified number of characters from the left and right of the given string respectively. Some special cases are described here:

Condition Left / Right returns Length ≥ length of string Returns the whole string.

Length = 0 Returns an empty string (""). Length < 0 Exception. Results in runtime error if not handled.

It does not make sense to pass a negative length to string functions.  However, if you pass a variable as the length, you need to check for unexpected cases.

Exception handling is not included in this book. Anyway, exceptions in  string functions are not meant to be handled.

Here is an example:

Dim TestString As String = "Hello World!" Dim result As String

result = Left(TestString, 5) ' Returns "Hello". result = Left(TestString, 100) ' Returns "Hello World!". result = Left(TestString, 0) ' Returns "".

result = Right(TestString, 5) ' Returns "orld!". result = Right(TestString, 100) ' Returns "Hello World!". result = Right(TestString, 0) ' Returns "". Details of string functions 11 Mid function

Mid function extracts the specified number of characters beginning from the given starting position. The position is one-based, i.e. the first character of a string has a position of 1. Some special cases are described here:

Condition Mid returns Length is not specified Returns everything starting from the given position.

Start = 1 Return is same as Left.

Start > length of string Returns an empty string (""). Start ≤ 0 or Length < 0 Exception. Results in runtime error if not handled.

Here is an example:

Dim TestString As String = "Mid Function Demo" Dim result As String

result = Mid(TestString, 1, 3) ' Returns "Mid". result = Mid(TestString, 14, 4) ' Returns "Demo". result = Mid(TestString, 5) ' Returns "Function Demo". 12 Introduction to Visual Basic (Part 2) Trim function

Trim function removes white spaces in the beginning and the end of the string. This is used for sanitising user inputs because users may add unneeded spaces to the input. The spaces at the middle of the strings are not removed. However, we should note that “white space” in this function also includes ideographic space (code point 12288), which is commonly used in CJK (Chinese, Japanese and Korean) text.

Dim TestString As String = " Visual Basic "

' Returns "Visual Basic". Dim result As String = Trim(TestString)

If you want to remove white spaces at the beginning of the string only,  use LTrim. For the end of the string, use RTrim.

UCase and LCase functions

UCase and LCase functions convert all letters in the strings to upper case and lower case respectively. Other characters, such as digits, are not affected.

In addition to “a” to “z”, a lot of characters have an upper case or a  lower case variant. For example, the upper case variant of the “π” is “Π”.

Dim TestString As String = "Hello World 1234!" Dim result As String

result = UCase(TestString) ' Returns "HELLO WORLD 1234!". result = LCase(TestString) ' Returns "hello world 1234!".

Beware of UCase("i") and LCase("I"). In Turkish, they evaluate to  "İ" and "ı" respectively. Details of string functions 13 AscW and ChrW functions

AscW returns the Unicode code point of the first character of the string. And ChrW returns a character corresponding to the Unicode code point. However, these functions work only if the character has a Unicode code point of 65535 or below.

Dim code As Integer code = AscW("A") ' Returns 65. code = AscW("Apple") ' Returns 65. code = AscW("a") ' Returns 97. code = AscW("0") ' Returns 48. code = AscW(vbCrLf) ' Returns 13.

Dim character As String character = ChrW(65) ' Returns "A". character = ChrW(97) ' Returns "a". character = ChrW(51) ' Returns "3". character = ChrW(33) ' Returns "!".

Class Work

Evaluate the following VB.NET expressions. In this exercise, UCase and LCase are executed in American English.

VB.NET expression Result

Right("S.2", 1) & Left("Cactus", 1)

UCase(LCase("TeStInG"))

Len(Mid(Trim(" very good "), 7, 4))

ChrW(100) >= "E"

ChrW(AscW("Z") + 20)

AscW(UCase("basic"))

AscW(Mid(vbCrLf, 2)) 14 Introduction to Visual Basic (Part 2) Integrated example: ROT13 cipher

Here we implement a toy cipher called “ROT13” (rotate characters by 13 places). While ROT13 cannot safely keep secrets, it can be used to hide spoilers.

Module Module1 Function RotateCharBy13(ch As String) As String If ch >= "A" And ch <= "Z" Then Return ChrW((AscW(ch) - 65 + 13) Mod 26 + 65) End If If ch >= "a" And ch <= "z" Then Return ChrW((AscW(ch) - 97 + 13) Mod 26 + 97) End If Return ch End Function

Sub Main() Console.WriteLine("ROT13 - Rotate by 13 places") Console.WriteLine("Enter the text to process:") Dim s As String = Console.ReadLine()

Console.WriteLine() Console.WriteLine("Processed text:")

Dim length = Len(s) Dim pos = 1 Do Until pos > length Console.Write(RotateCharBy13(Mid(s, pos, 1))) pos += 1 Loop Console.WriteLine()

Console.ReadLine() End Sub End Module Details of string functions 15

Now see the cipher into action. The second ROT13 operation cancels the first.

ROT13 - Rotate by 13 places ======Enter the text to process: Visual Basic is awesome!

Processed text: Ivfhny Onfvp vf njrfbzr!

ROT13 - Rotate by 13 places ======Enter the text to process: Ivfhny Onfvp vf njrfbzr!

Processed text: Visual Basic is awesome!

RotateCharBy13 in this example is not a robust implementation because the behavior is undefined if multiple characters are passed to  ch. However, the fix of this problem is too complicated to be discussed in this book. 16 Introduction to Visual Basic (Part 2) 1.3 Comparison of strings

Strings are compared in a way similar to how words are ordered in a dictionary. A word appearing in the beginning of the dictionary is considered less than a word in the end of the dictionary, e.g. “apple” is less than “umbrella”. We call this lexicographical order. To see which string is greater, the first characters of the two strings are compared. If the characters are different, then the comparison is finished. Otherwise, the second characters are compared, so on. If all the characters of both strings are equal, then the strings are equal. However, if the characters of only one of the strings are used up in the comparison, and all the compared characters are equal, then the longer string is greater. Here are a few results of string comparison (written as Boolean expressions that are true).

Comparison result Reason "banana" < "cat" The first characters are different, with “b” less than “c”. "formal" < "forward" The fourth characters are different, with “m” less than “w”. "other" < "otherwise" All characters from “other” are used up. "car" = "car" All characters are the same.

If the strings compared contain capital letters, digits, symbols, Chinese characters, etc., the comparison is more complex. Different comparison methods produce different results even for comparing the same strings. In this section, we discuss only binary comparison of strings in VB.NET, which is the default method. It means the strings are compared with their UTF-16 encoded values, code unit by code unit. For characters encoded with one UTF-16 code unit, this means to compare their Unicode code point. Comparison of strings 17

You can refer to the ASCII table for the Unicode code point of letters, digits and some symbols. And you are expected to recite a few facts: 1. “A” is the smallest capital letter, and “Z” is the largest capital letter. Comparison of small letters is similar. 2. “0” is the smallest of the digits, and “9” is the largest. 3. Capital letters are always less than small letters 4. Digits are always less than letters, capital or small. 5. White space is less than all other characters, except for control characters such as CR or LF. 6. Chinese characters have a Unicode code point of 12288 or more. For example, “鄧” has a Unicode code point of 37159 (or U+9127). However, the Unicode code points of Chinese characters are not ordered in a specific order. Note: you are not required to recite the ASCII table except for the facts listed above. Class work

Evaluate the following VB.NET expressions. Strings are compared using binary comparison. Note: results are either True or False .

VB.NET expression Result

"pointer" >= "pointing"

"Flower" < "flower"

Trim(" Visual Basic ") <= " Visual Basic "

Mid("okay", 2, 2) > Mid("okay", 4, 2)

Len("human") < 5 Or Strings.Right("able", 2) = "le" 18 Introduction to Visual Basic (Part 2) 1.4 String matching

In this section, we discuss a few string matching functions.

Details of string comparison apply to string matching. In addition,  String.StartsWith and InStr may give incorrect results on arbitrary UTF-16 strings.

String.StartsWith and String.EndsWith methods

String.StartsWith and String.EndsWith are methods of String , which check if a string starts with or ends with certain substring respectively. The return values of there methods are Boolean , i.e. either True or False . Note: a method is a procedure associated with an object. Despite the difference in the name, a method is essentially the same as other procedures. The following example checks a file by its name to see if it is a Microsoft Word file.

Console.Write("Enter the name of the file: ") Dim filename As String = Console.ReadLine()

Dim filenameUpper As String = UCase(filename) If filenameUpper.EndsWith(".DOCX") Then Console.WriteLine("It is a DOCX file.") ElseIf filenameUpper.EndsWith(".DOC") Then Console.WriteLine("It is a DOC file.") Else Console.WriteLine("It is not a Microsoft Word file.") End If

Enter the name of the file: test.docx It is a DOCX file. String matching 19 InStr function

To locate one string within another string, you can use the InStr function. The syntax of the InStr function is as follows:

[variable =] InStr(String1, String2) [variable =] InStr(Start, String1, String2)

The meanings of the parameters are listed below:

Parameter Meaning Start The starting position of the search. Matches before Start are (Optional) ignored. If omitted, then Start is 1. The position is one-based. String1 The string to be searched in. Also known as haystack. String2 The string to search for. Also known as needle.

And here is the return:

Condition InStr returns String2 is found within String1. Position where the first match begins (one- based) String2 is not found. 0 String1 is empty. 0 Start > length of String1. 0 String2 is empty, but String1 is Start not empty. Start < 1 Exception. Results in runtime error if not handled. 20 Introduction to Visual Basic (Part 2)

To see how the InStr function works, it is best to read an example:

Console.Write("Enter a string: ") Dim str1 As String = Console.ReadLine()

Console.Write("Enter the substring to search for: ") Dim str2 As String = Console.ReadLine()

Dim pos As Integer = InStr(str1, str2) If pos > 0 Then Console.Write("""{0}"" is found in positions {1}", str2, pos) Do pos = InStr(pos + 1, str1, str2) If pos = 0 Then Exit Do End If Console.Write(", {0}", pos) Loop Console.WriteLine(".") Else Console.WriteLine("""{0}"" is not found.", str2) End If

Enter a string: Seeing InStr work is eeeasy. Enter the substring to search for: ee "ee" is found in positions 2, 22, 23. String matching 21 Class Work

Evaluate the following VB.NET expressions. Strings are compared and matched using binary comparison.

VB.NET expression Result

"abc".StartsWith("ab")

"35th".EndsWith("TH")

Instr("aeroplane", "a")

Instr(3, "aeroplane", "a")

Instr(8, "aeroplane", "a")

Instr("ab", "able")

Left("flyer", InStr("flyer", "y"))

Mid("Zepellin", InStr("Zepellin", "l")) 22 Introduction to Visual Basic (Part 2) Exercise 1

1. Write a program that asks the user to enter his/her name and class. Then output the sentence “[Name] is a Secondary [x] student.”, where [Name] is the name of the student, and [x] is the form of the student. The class should contain one digit followed by one letter (in either upper case or lower case). If not, output “Is [class] really a class?” instead. Here are some sample outputs:

Enter the name: Darius Lui Enter the class: 4F Darius Lui is a Secondary 4 student.

Enter the name: Mary Kwok Enter the class: 1+ Is 1+ really a class?

2. Write a program to see if a word is a palindrome, i.e. the word reads the same forward and backwards. The program should produce the following output:

Enter a word: madam The word is a palindrome.

Enter a word: program The word is not a palindrome.

3. Modify the program in the previous question to ignore letter cases, spaces, and punctuations. Now it should identify palindrome sentences like “Borrow or rob?”. Exercise 23

4. Write a program that reads a date in the format D/M/Y (e.g. 21/2/2013, 5/11/2013), and then output a sentence like “Day: 21, Month: 2, Year: 2013”. The date always comes with two “/” symbols. In this question, you can output the three substrings without validation. Note: the validation part of this question is a good exercise, but please leave it out before you finish the next chapter.

Enter a date: 21/2/2013 Day: 21, Month: 2, Year: 2013

5. Write a Caesar cipher. The Caesar cipher encodes a message by rotating each letter in the message three places down the alphabet. Your program should be able to encode and decode messages, like the sample output below:

Caesar Cipher ======Encode or Decode? (E/D) E Enter the message: THE FIVE BOXING WIZARDS JUMP QUICKLY Result: QEB CFSB YLUFKD TFWXOAP GRJM NRFZHIV

Caesar Cipher ======Encode or Decode? (E/D) D Enter the message: QEB CFSB YLUFKD TFWXOAP GRJM NRFZHIV Result: THE FIVE BOXING WIZARDS JUMP QUICKLY

6. Write a program that reverses the order of words in the input. You can assume that two words are always separated by a space character. Here is a sample output:

Enter a sentence: string processing is difficult Order of words reversed: difficult is processing string

7. (a) Write a Vigenère cipher. (b) Modify the cipher to make it stronger. (Note: this is an open-ended question.) 24 Introduction to Visual Basic (Part 2) Chapter 2 Validation of Input

In this section, we discuss how to validate input. Data validation is one of the ways to make sure that only correct data are processed. If wrong data is inputted into a program, the processed output becomes meaningless. In worse cases, a specially crafted input can be used to exploit the absence of data validation. This can result in security incidents such as: Leakage of sensitive information, e.g. bank account passwords or encryption keys. This can result in financial loss or many other serious consequences. Information leakage does often hit news headlines, such as the 2016 Democratic National Committee email leak incident, and the Ashley Madison data breach in 2015. Execution of arbitrary code from a remote computer. This can be used for all kinds of malicious activities, such as running ransomware and leaking information. Access of computer accounts without checking for credentials. Crashing or freezing the computer program. This is a type of denial-of-service (DoS) attack. Some of these attacks can be further developed to execute arbitrary code. There are many types of data validation, such as: Range check. For example, the month of a date should lie between 1 and 12. Format check, i.e. check that the data is in a specific pattern. For example, dates must be in the format D/M/Y or DD/MM/YYYY. You can search the web to know more types of data validation. However, data validation are not limited to these types. For example: Someone enters a day in a certain format. Besides checking the format, we also check whether the year, month and day entered form a valid date. Someone sets a new password to his or her account. To see whether the password is weak, we check the length of the password, check the variety of characters, and compare the password with a list of known passwords. Range check 25 2.1 Range check

Doing a range check is simple. All you need to do is shown in the following example:

Sub Main() ' Preceding code (omitted) If month < 1 Or month > 12 Then Console.Write("The month should be between 1 and 12.") Return End If ' Succeeding code (omitted) End Sub

The If block containing the Return statement is called a guard clause. When validation fails, the guard clause can be used for early exit. However, range check is best done with procedures to improve readability:

Function IsValidMonth(month As Integer) As Boolean Return month >= 1 And month <= 12 End Function

Sub Main() ' Preceding code (omitted) If Not IsValidMonth(month) Then Console.Write("The month should be between 1 and 12.") Return End If ' Succeeding code (omitted) End Sub

Using procedures for validation has the advantage of code reuse. This also allows complex validation (e.g. whether a day, month and year combination forms a valid date) to be coded effectively. 26 Introduction to Visual Basic (Part 2) 2.2 Format check with TryParse

Parse method: what you have used implicitly

Every numeric data type in VB.NET has a Parse method and a TryParse method. So far you have been using Parse method implicitly:

Dim n As Integer = Console.ReadLine()

This statement is implicitly converted to the following during compilation:

Dim n As Integer = Integer.Parse(Console.ReadLine())

Parse method checks for the following errors: empty string invalid format overflow A numeric data type can represent a certain range of numbers. For example, the range representable by Integer is from −2 147 483 648 to 2 147 483 647. If the input string is a number outside this range, then overflow happens.

Parse throws an exception when one of the three errors is encountered. Unless we handle the exception, that exception becomes a runtime error. Format check with TryParse 27 TryParse method: Parse without exceptions

To avoid the exceptions, we can use TryParse instead. Here is the definition of TryParse method of Integer , Single and Double in MSDN:

Public Shared Function TryParse ( s As String, ByRef result As Integer ) As Boolean

The first argument ( s ) of the function is the input. And the second argument ( result ) is the output, which is passed by reference. The function returns a Boolean , being True if parsing succeeds. If parsing fails, the function returns False with the value 0 stored in result .

The use of TryParse is shown in the following example:

Dim n As Integer If Not Integer.TryParse(Console.ReadLine(), n) Then Console.WriteLine("The input is not an integer.") End If

You can also ask the user to input again if validation fails:

Dim n As Integer Do Console.Write("Enter the value of n: ") If Integer.TryParse(Console.ReadLine(), n) Then Exit Do End If Console.WriteLine("You should input an integer. Try again.") Loop 28 Introduction to Visual Basic (Part 2)

Since the code is quite long here, it is preferable to put the code in a Function to improve readability. Here is an example:

Function InputIntegerUntilSuccess(prompt As String) As Integer Do Console.Write(prompt) Dim number As Integer If Integer.TryParse(Console.ReadLine(), number) Then Return number End If Console.WriteLine( "You should input an integer. Try again.") Loop End If

Option Strict On

Now you have learned to use TryParse to validate numbers. From now on, you should add Option Strict On to the beginning every .vb file you write:

Option Strict On

Module Module1 ' Insert code here. End Module

This forbids a few types of implicit conversions, including the implicit conversion from string to numbers. Having Option Strict On protects you from making a few bad coding habits.

Dim n As Integer = Console.ReadLine() and similar statements do not work with Option Strict On. If needed, use Integer.Parse  and similar methods instead. See the beginning of this section to see how to use these methods. Exercise 29 Exercise 2

1. Pick any exercise question in the previous chapters. Write the program again with input validation. Do this on as many exercise questions as you like. You may want to redesign your program again, so please write from scratch.

2. Pick any exercise question in the previous chapters, preferably the one you selected in the last question. Edit or rewrite the program with Option Strict On . Again, do this on as many exercise questions as you like.

3. Check whether a given year, month and day form a valid date in the Gregorian calendar. You should write this as a function, e.g.

Function IsValidDate(year As Integer, month As Integer, day As Integer) As Boolean 30 Introduction to Visual Basic (Part 2) Glossary

ASCII American Standard Code for Information Interchange, a popular character set. boundary case A special case that one or more input is at or just beyond its maximum or minimum limits. Big5 A character encoding used in , Hong Kong, and Macau for Traditional Chinese characters. character A minimal unit of text. Can be a letter, a digit, a punctuation mark, a white space, and other things. character set A set of characters where each character corresponds to a unique number. CJK Chinese, Japanese and Korean languages. control characters A character which is not a written symbol. Examples are CR and LF. Also known as non-printing character. data validation The process of ensuring that input data is valid before processing. format check Checks that data is in a specific format, e.g. dates and telephone numbers. GBK Guojia Biaozhun Kuozhan, a character encoding for simplified Chinese characters. Despite the name, GBK is not an official standard. lexicographical order A mathematical order similar to how dictionary order words. Glossary 31 method A procedure in the context of objects. range check Checks that numerical data is within a specified range of possible values. string A sequence of characters. Unicode The character set that can be used to represent text in different languages simultaneously. UTF-16 One of the character encoding under Unicode. Used to store strings in .NET platform.