introduction to 2lwc1/files/files/s3_cl... · 6 class work 1.1.3 decide whether each of the...

32
A revised course with - Concise concepts - Hands on class work - Plenty of examples - Programming exercises Introduction to Copyright © HKTA Tang Hin Memorial Secondary School 2012-14 2 Version 1.2

Upload: others

Post on 25-Aug-2020

1 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Introduction to 2lwc1/files/files/s3_cl... · 6 Class Work 1.1.3 Decide whether each of the following is True or False. VB expression Result 4 > 2 And 1 = 3 20 < -5 Or 3 >=

A revised course with

- Concise concepts

- Hands on class work

- Plenty of examples

- Programming exercises

Introduction to

Copyright © HKTA Tang Hin Memorial Secondary School 2012-14

2

Version 1.2

Page 2: Introduction to 2lwc1/files/files/s3_cl... · 6 Class Work 1.1.3 Decide whether each of the following is True or False. VB expression Result 4 > 2 And 1 = 3 20 < -5 Or 3 >=

2

Contents

Chapter 1 Flow Control (2) ..................................................................................................... 4

1.1 Logical operators .................................................................................................... 4

1.1.1 Revision of If...Then...Else statement ........................................................ 4

1.1.2 Logical operators ........................................................................................ 4

1.1.3 Operator precedence ................................................................................. 5

1.2 If...Then...Else statement with logical operators ................................................... 6

1.3 Nested If...Then...Else statements ......................................................................... 7

1.4 Exit Sub and End statements ................................................................................. 8

1.4.1 Exit Sub statement ..................................................................................... 8

1.4.2 End statement ............................................................................................ 8

Exercise 1 ........................................................................................................................... 9

Chapter 2 Generating Random Numbers ............................................................................. 10

2.1 Rnd function ......................................................................................................... 10

2.2 Initialize Rnd with Randomize.............................................................................. 10

2.3 A virtual dice using Rnd function ......................................................................... 11

2.4 Generating random integers within a certain range ........................................... 12

2.5 Miscellaneous examples ...................................................................................... 13

Exercise 2 ......................................................................................................................... 14

Chapter 3 More on MsgBox and InputBox ........................................................................... 15

3.1 MsgBox ................................................................................................................. 15

3.1.1 MsgBox syntax ......................................................................................... 15

3.1.2 Showing a custom title ............................................................................. 15

3.1.3 Showing multiline message in a MsgBox ................................................. 16

3.1.4 Add an icon inside the MsgBox ................................................................ 18

3.1.5 Showing different buttons in the MsgBox ............................................... 20

3.2 InputBox ............................................................................................................... 22

3.2.1 InputBox syntax ....................................................................................... 22

3.2.2 InputBox examples................................................................................... 22

3.3 Miscellaneous example ........................................................................................ 24

Page 3: Introduction to 2lwc1/files/files/s3_cl... · 6 Class Work 1.1.3 Decide whether each of the following is True or False. VB expression Result 4 > 2 And 1 = 3 20 < -5 Or 3 >=

3

Chapter 4 String Manipulation ............................................................................................. 25

4.1 Introduction to string functions ........................................................................... 25

4.2 String functions and their special cases ............................................................... 26

4.2.1 Len function ............................................................................................. 26

4.2.2 Strings.Left, Strings.Right functions ......................................................... 26

4.2.3 Mid function ............................................................................................. 27

4.2.4 UCase and LCase functions ...................................................................... 27

4.2.5 Trim function ............................................................................................ 27

4.3 String comparison ................................................................................................ 28

4.4 Using InStr function to extract contents from a string ........................................ 30

Exercise 4 ......................................................................................................................... 32

Alphabetical Index ................................................................................................................... 32

Page 4: Introduction to 2lwc1/files/files/s3_cl... · 6 Class Work 1.1.3 Decide whether each of the following is True or False. VB expression Result 4 > 2 And 1 = 3 20 < -5 Or 3 >=

4

Chapter 1 Flow Control (2)

1.1 Logical operators

1.1.1 Revision of If...Then...Else statement

In the last book, we have learnt how to use If...Then...Else statement. The syntax is listed

here for your reference:

If condition Then

Statement1

Statement2

...

Else

Statement3

Statement4

...

End If

1.1.2 Logical operators

We often make decisions based on the results of two or more comparisons. For example,

when you check whether an examination mark is valid, you will check whether the mark is

between 0 and 100 (both inclusive). The logical operator And is needed to join the

conditions together, i.e.

If marks >= 0 And marks <= 100 Then

In this course, three logical operators are studied: Not, And, Or. Here are their meanings:

Operator Meaning Syntax

Not Negation. True/False are inverted. Not condition1

And See if all conditions are true. condition1 And condition2

Or See if one or more conditions are true. condition1 Or condition2

Page 5: Introduction to 2lwc1/files/files/s3_cl... · 6 Class Work 1.1.3 Decide whether each of the following is True or False. VB expression Result 4 > 2 And 1 = 3 20 < -5 Or 3 >=

5

Class Work 1.1.1

Complete the following truth tables by writing down the results (True or False):

And Or Not

a b a And b a b a Or b x Not x

True True True True True

True False True False False

False True False True

False False False False

1.1.3 Operator precedence

The evaluation of expressions in Visual Basic is ordered by its operator precedence below.

(Note: Not is executed before And, and And is executed before Or.)

Low

est ←

− −

− −

− −

− −

→ H

igh

est 11 Exponentiation ^

10 Unary identity and negation (unary)+ (unary)–

9 Multiplication and floating-point division * /

8 Integer division \

7 Modulus arithmetic Mod

6 Addition and subtraction + –

5 String concatenation &

4 Relational/comparison operators = <> < <= > >=

3 Negation Not

2 Conjunction And

1 Inclusive disjunction Or

Class Work 1.1.2

Convert the following to Visual Basic conditions. (Names of the variables are underlined.)

Comparisons Visual Basic condition

If the mark is outside the range 0 ≤ 𝑥 ≤ 100 mark < 0 Or mark > 100

If the guess is between 5 and 9. (Both inclusive.)

If the day is “Mon” or “Tue”

If the sex is “M” and the weight is greater than

80 (kg).

If the age is not less than 65, and today is “Sat”.

Page 6: Introduction to 2lwc1/files/files/s3_cl... · 6 Class Work 1.1.3 Decide whether each of the following is True or False. VB expression Result 4 > 2 And 1 = 3 20 < -5 Or 3 >=

6

Class Work 1.1.3

Decide whether each of the following is True or False.

VB expression Result

4 > 2 And 1 = 3

20 < -5 Or 3 >= 3

-5 <= -7 Or 3 / 2 > 2

1 > -2 And 5 / 7 >= 3 / 5

Not (5 ^ 2 >= 2 ^ 5)

Not (6 <= -2 And 7 > 12)

1 > 2 And 3 = 4 Or 5 <= 6

Not True And Not False

Class Work 1.1.4

Convert the following mathematical expressions to Visual Basic conditions:

Mathematical expression Visual Basic condition

0 < 𝑎 < 18

𝑥 ≤ 𝑦 ≤ 𝑧

𝑎 > 0 > 𝑏

1.2 If...Then...Else statement with logical operators

Example 1.2.1 If statement with multiple conditions

Public Class Form1

Private Sub Button1_Click(...) Handles Button1.Click

Dim age As Integer = Val(TextBoxAge.Text)

Dim sex As String = TextBoxSex.Text

If age > 0 And age < 18 And sex = "F" Then

MsgBox("Welcome to the dreamland!")

Else

MsgBox("No entry.")

End If

End Sub

End Class

TextBoxAge

TextBoxSex

Page 7: Introduction to 2lwc1/files/files/s3_cl... · 6 Class Work 1.1.3 Decide whether each of the following is True or False. VB expression Result 4 > 2 And 1 = 3 20 < -5 Or 3 >=

7

1.3 Nested If...Then...Else statements

You can put an If...Then...Else statement inside another statement block, such as another

If...Then...Else statement. Please see an example below:

Example 1.3.1 Nested If...Then...Else statements – Fee of an event

Public Class Form1

Private Sub Form1_Load(...) Handles MyBase.Load

Dim s As String

s = InputBox("Are you a member? (Y/N)")

If s = "Y" Or s = "y" Then

MsgBox("Members - Free of charge.")

Else

s = InputBox("Non-members: input discount code (ESC to cancel).")

If s = "5318" Then

MsgBox("Discount #1 awarded. The fee of entry is $2.")

ElseIf s = "2407" Then

MsgBox("Discount #2 awarded. The fee of entry is $5.")

Else

MsgBox("No discount. The fee of entry is $10.")

End If

End If

Me.Close()

End Sub

End Class

Page 8: Introduction to 2lwc1/files/files/s3_cl... · 6 Class Work 1.1.3 Decide whether each of the following is True or False. VB expression Result 4 > 2 And 1 = 3 20 < -5 Or 3 >=

8

1.4 Exit Sub and End statements

1.4.1 Exit Sub statement

The Exit Sub statement immediately exits the current Sub procedure. It is useful in

validation of data, i.e. Exit Sub when the input data is invalid.

Example 1.4.1 Area of rectangle with simple validation

Public Class Form1

Private Sub Button1_Click(...) Handles Button1.Click

' Read data. Exit Sub if validation fails.

Dim l As Double = Val(TextBox1.Text)

If l <= 0 Then

LabelResult.Text = "Error!!!"

Exit Sub

End If

' Do calculations with validated input

Dim area As Double = l * l

LabelResult.Text = area

End Sub

End Class

1.4.2 End statement

The End statement exits the program immediately.

Of course, it is possible to exit a program by other methods, such as calling Me.Close().

Example 1.4.2 End statement and Me.Close() statement Public Class Form1

Private Sub ButtonNewForm_Click(...) Handles ButtonNewForm.Click

' Make a copy of Form1 (not required in syllabus)

Dim f As New Form1

f.Show()

End Sub

Private Sub ButtonCloseForm_Click(...) Handles ButtonCloseForm.Click

' Close current form. (End program if the initial form is closed.)

Me.Close()

End Sub

Private Sub ButtonEndProg_Click(...)

Handles ButtonEndProg.Click

' End program.

End

End Sub

End Class

LabelResult

ButtonNewForm

ButtonCloseForm

ButtonEndProg

Page 9: Introduction to 2lwc1/files/files/s3_cl... · 6 Class Work 1.1.3 Decide whether each of the following is True or False. VB expression Result 4 > 2 And 1 = 3 20 < -5 Or 3 >=

9

Exercise 1

1. Convert the following mathematical expressions to Visual Basic conditions:

Mathematical expression* Visual Basic condition

50 ≤ 𝑥 < 60

−1 < 𝑏 < 1

𝑝 ≥ 𝑞 ≥ 𝑟 > 0

2. Write down the following conditions without using the Not operator:

Condition Without Not operator

Not (marks >= 0 And marks <= 100)

Not (num < 0 Or num >=10)

3. Ask the user to input the age and sex. Output the result based on the table below:

Age Sex M F

≥ 18 Max Woman

< 18 Boy Girl

4. The examination of the Computer subject in Acme School consists of two papers:

theory and practical. The full marks are 100 in both papers. Write a program to

calculate the overall grades, which is listed in the following table.

Condition Grade

Less than 50 marks in any of the papers

(regardless of all other conditions) Fail

Having 80 or more marks in both papers Distinction

Having an average mark of 70 or above Merit

Otherwise Pass

* To be exact, “50 ≤ 𝑥 < 60” should be called a “predicate” but not an expression. The term “expression” is

used here only to avoid introducing a mathematical term in university level.

Page 10: Introduction to 2lwc1/files/files/s3_cl... · 6 Class Work 1.1.3 Decide whether each of the following is True or False. VB expression Result 4 > 2 And 1 = 3 20 < -5 Or 3 >=

10

Chapter 2 Generating Random Numbers

2.1 Rnd function

The Rnd function returns a number less than one, but greater than or equal to zero, i.e.

0 ≤ 𝑥 < 1

The syntax is of Rnd function is simply Rnd().

The following program outputs a result of Rnd function each time you press the button.

Run the program several times and see what is wrong.

Example 2.1.1 Incorrect use of Rnd function

Public Class Form1

Private Sub Button1_Click(...) Handles Button1.Click

TextBox1.AppendText(Rnd() & vbCrLf)

End Sub

End Class

2.2 Initialize Rnd with Randomize

To make the Rnd function generate different series

of numbers, we call the Randomize function before

using the Rnd function. Randomize should only be

called once only in the whole program.

Usually, we call “Randomize()” in the MyBase.Load event, like the example below:

Example 2.2.1 Correct use of Rnd function

Public Class Form1

Private Sub Form1_Load(...) Handles MyBase.Load

Randomize()

End Sub

Private Sub Button1_Click(...) Handles Button1.Click

TextBox1.AppendText(Rnd() & vbCrLf)

End Sub

End Class

TextBox1

(Set property “Multiline” to True.)

Page 11: Introduction to 2lwc1/files/files/s3_cl... · 6 Class Work 1.1.3 Decide whether each of the following is True or False. VB expression Result 4 > 2 And 1 = 3 20 < -5 Or 3 >=

11

2.3 A virtual dice using Rnd function

In daily life, we use dice for playing games. To throw a die in Visual Basic, use the following

statement:

[variable] = Int(Rnd() * 6) + 1

To illustrate this statement, we list all possible values of Rnd() in the table below:

(Note: The function Int rounds down a number to the nearest integer.)

Rnd() Rnd() * 6 Int(Rnd() * 6) Int(Rnd() * 6) + 1

≥ 0 and <1

6 ≥ 0 and < 1 0 1

≥1

6 and <

2

6 ≥ 1 and < 2 1 2

≥2

6 and <

3

6

≥3

6 and <

4

6

≥4

6 and <

5

6

≥5

6 and < 1

Example 2.3.1 Throwing a die with computer

Public Class Form1

Private Sub Form1_Load(...)

Handles MyBase.Load

Randomize()

End Sub

Private Sub Button1_Click(...) Handles Button1.Click

Dim a As Integer = Int(Rnd() * 6 + 1)

TextBox1.AppendText(a & " ")

End Sub

End Class

Page 12: Introduction to 2lwc1/files/files/s3_cl... · 6 Class Work 1.1.3 Decide whether each of the following is True or False. VB expression Result 4 > 2 And 1 = 3 20 < -5 Or 3 >=

12

2.4 Generating random integers within a certain range

We can modify the statement Int(Rnd() * 6) + 1 to generate random integers that

fall within a certain range. Take Int(Rnd() * 4) + 8 as an example:

Rnd() Rnd() * 4 Int(Rnd() * 4) Int(Rnd() * 4) + 8

≥ 0 and <1

4 ≥ 0 and < 1

≥1

4 and <

2

4

≥2

4 and <

3

4

≥3

4 and < 1

From the table, we know that the statement generates random integers from 8 to 11

inclusive. Also, “4” is the number of possible outcome, and “8” is the minimum outcome.

The total number of possible outcomes can be calculated by 𝑚𝑎𝑥 − 𝑚𝑖𝑛 + 1, where

𝑚𝑎𝑥 and 𝑚𝑖𝑛 are the maximum and minimum outcome respectively. Therefore, we can

generate integers inside a range by using the formula below:

[variable] = Int(Rnd() * (max – min + 1)) + min

Class Work 2.4

Write a Visual Basic statement to generate the random numbers below.

Random number VB code

An integer from 1 to 6 inclusive Int(Rnd() * 6) + 1

An integer from 1 to 5 inclusive

An integer from 10 to 20 inclusive

An integer from 25 to 30 inclusive

An integer from 50 to 100 inclusive

An integer from 0 to 2 inclusive

An integer from -5 to 5 inclusive

The sum of the values of 2 dice (the

possible values of each die are 1 to 6)

Page 13: Introduction to 2lwc1/files/files/s3_cl... · 6 Class Work 1.1.3 Decide whether each of the following is True or False. VB expression Result 4 > 2 And 1 = 3 20 < -5 Or 3 >=

13

2.5 Miscellaneous examples

Example 2.5.1 Lucky draw

Public Class Form1

Private Sub Form1_Load(...)

Handles MyBase.Load

Randomize()

End Sub

Private Sub Button1_Click(...) Handles Button1.Click

Dim draw As Integer = Int(Rnd() * 100) + 1

LabelDraw.Text = draw

If draw <= 50 Then

LabelPrize.Text = "No Prize"

ElseIf draw <= 75 Then

LabelPrize.Text = "Small Prize"

ElseIf draw <= 90 Then

LabelPrize.Text = "Middle Prize"

ElseIf draw <= 99 Then

LabelPrize.Text = "Big Prize!"

Else

LabelPrize.Text = "JUMBO Prize!!!"

End If

End Sub

End Class

Example 2.5.2 Monopoly dice thrower

Public Class Form1

Private Sub Form1_Load(...) Handles MyBase.Load

Randomize()

End Sub

Private Sub Button1_Click(...) Handles Button1.Click

Dim n1 As Integer = Int(Rnd() * 6) + 1

Dim n2 As Integer = Int(Rnd() * 6) + 1

Dim total As Integer = n1 + n2

LabelDie1.Text = n1

LabelDie2.Text = n2

LabelTotal.Text = total

End Sub

End Class

LabelDie1 LabelDie2 LabelTotal

LabelDraw

LabelPrize

Page 14: Introduction to 2lwc1/files/files/s3_cl... · 6 Class Work 1.1.3 Decide whether each of the following is True or False. VB expression Result 4 > 2 And 1 = 3 20 < -5 Or 3 >=

14

Exercise 2

1. Write a program that throws two dice, one for the player and the other for the

computer. Display the values of both dice. Also, compare the values of the dice. If the

value of the player’s die is larger, output “You win!” If the value of computer’s die is

larger, output “You lose!” If the values of both dice are equal, output “Draw!”

2. Write a simple number guessing game. The details of the game are described below:

(a) First, the user clicks the “Start Game” button. When the button is clicked, the

computer generates a secret number, which is an integer between 1 and 100

inclusive.

(b) Then the user enters a guess and clicks the “Guess” button. The computer

compares the guess with the secret number generated in (a), and then output

one of the following messages: “Too big!”, “Too small!”, or “Correct!”

3. Modify the program in the question 2, in order to make the program output the

number of guesses made by the user, in addition to all the requirements of the last

question.

4. Write a program that asks the player to do simple arithmetic calculations. The

computer generates an arithmetic expression with two random numbers and one

random sign (plus or minus), and ask the user to enter the answer. When the user

enters the answer, the computer will check if the answer is correct or not.

(Challenges: make sure the result of the subtraction is not less than zero. Include

multiplication and division in the program. Requires the user to input the answer

within certain time. Add calculate a score for the player based on his/her

performance.)

Page 15: Introduction to 2lwc1/files/files/s3_cl... · 6 Class Work 1.1.3 Decide whether each of the following is True or False. VB expression Result 4 > 2 And 1 = 3 20 < -5 Or 3 >=

15

It is easy to forget to add the second comma in the MsgBox function.

Chapter 3 More on MsgBox and InputBox

In Chapter 5, you have leant to handle output with MsgBox and input with InputBox. In

this chapter, we study the details of these two functions.

3.1 MsgBox

3.1.1 MsgBox syntax

The syntax of MsgBox is listed below:

[variable = ] MsgBox(Prompt, Buttons, Title)

The MsgBox function returns an integer which indicates the button pressed by the user in

the message box. The meanings of the parameters are listed below:

Parameter Meaning

Prompt The message inside the MsgBox.

Button (Optional) The buttons, icons, and other options of the MsgBox.

Title (Optional) The title of the MsgBox. If you don’t specify the title,

then the title is the name of the application.

3.1.2 Showing a custom title

If the “Ok” button is good enough for your

MsgBox, you can skip the parameter Buttons.

However, there must be two commas between Prompt and Title, so Title is the third

parameter of the function.

MsgBox("The message...", , "Title")

Page 16: Introduction to 2lwc1/files/files/s3_cl... · 6 Class Work 1.1.3 Decide whether each of the following is True or False. VB expression Result 4 > 2 And 1 = 3 20 < -5 Or 3 >=

16

3.1.3 Showing multiline message in a MsgBox

To show a long message, you should split the message into multiple lines, and join these

lines using the constant vbCrLf. Here is an example:

MsgBox("First line," & vbCrLf & "second line.", , "Title")

The constant vbCrLf is similar to the Enter key in the keyboard. To add some empty space

between two paragraphs, you should join two vbCrLf together. For example,

MsgBox("Merry Christmas and Happy New Year!" &

vbCrLf & "Have a nice holiday!!!" & vbCrLf & vbCrLf &

"But don't forget the exam after the holidays!", ,

"A happy note...")

Page 17: Introduction to 2lwc1/files/files/s3_cl... · 6 Class Work 1.1.3 Decide whether each of the following is True or False. VB expression Result 4 > 2 And 1 = 3 20 < -5 Or 3 >=

17

Class Work 3.1.1

Write down the MsgBox statements that create the following dialog boxes.

Dialog box MsgBox statement

(The title is NOT specified in this

dialog box.)

Page 18: Introduction to 2lwc1/files/files/s3_cl... · 6 Class Work 1.1.3 Decide whether each of the following is True or False. VB expression Result 4 > 2 And 1 = 3 20 < -5 Or 3 >=

18

Try your best NOT to break a statement in the middle of a string.

3.1.4 Add an icon inside the MsgBox

We can display an icon inside an MsgBox. The icon will be

added to the left hand side of the message, like the screen

capture at the right.

To add an icon, simply put one of the constants below in

the Buttons parameter:

VB constant Value Icon When to use*

vbCritical 16

An error or problem has been occurred.

vbQuestion 32

Links to help topics. Don’t use for asking

questions.

vbExclamation 48

Warnings, i.e. a problem may arise in the future.

vbInformation 64

Don’t use.

Here is an example:

MsgBox("The marks must be between" & vbCrLf &

"0 and 100. Please try again.", vbCritical, "Invalid marks")

* Guidelines only. See http://msdn.microsoft.com/en-us/library/aa511277.aspx for more details.

Page 19: Introduction to 2lwc1/files/files/s3_cl... · 6 Class Work 1.1.3 Decide whether each of the following is True or False. VB expression Result 4 > 2 And 1 = 3 20 < -5 Or 3 >=

19

Class Work 3.1.2

Write down the MsgBox statements that create the following dialog boxes.

Page 20: Introduction to 2lwc1/files/files/s3_cl... · 6 Class Work 1.1.3 Decide whether each of the following is True or False. VB expression Result 4 > 2 And 1 = 3 20 < -5 Or 3 >=

20

The variable must NOT be called “return”, because “Return” is a reserved keyword.

3.1.5 Showing different buttons in the MsgBox

Besides icons, we can also put a set of buttons into an MsgBox. The sets of buttons

available are listed in the following table.

VB constant Value Buttons available in MsgBox

vbOkOnly 0 Ok

vbOkCancel 1 Ok, Cancel

vbAbortRetryIgnore 2 Abort, Retry, Ignore

vbYesNoCancel 3 Yes, No, Cancel

vbYesNo 4 Yes, No

vbRetryCancel 5 Retry, Cancel

To have both an icon and a set of buttons

simultaneously, simply add up the constants, like

the example below:

ret = MsgBox("Are you a boy?",

vbQuestion + vbYesNo)

When an MsgBox is shown, the user will select a

button in the MsgBox. Then, the MsgBox function returns an integer to indicate the button

pressed by the user*. You can save the result into a variable (e.g. to variable “ret” in the

example above). It is recommended to use the following constants to refer to the buttons:

VB constant Value Button Pressed

vbOk 1 Ok (or ESC key if vbOkOnly)

vbCancel 2 Cancel (or ESC key if Cancel button is available)

vbAbort 3 Abort

vbRetry 4 Retry

vbIgnore 5 Ignore

vbYes 6 Yes

vbNo 7 No

* If there is an Ok and/or a Cancel button, the user can also press the ESC key on the keyboard.

Page 21: Introduction to 2lwc1/files/files/s3_cl... · 6 Class Work 1.1.3 Decide whether each of the following is True or False. VB expression Result 4 > 2 And 1 = 3 20 < -5 Or 3 >=

21

Class Work 3.1.3

Write down the MsgBox statements that create the following dialog boxes, and store the

results in the variables given in the first lines of the answers.

Note: the title is NOT specified in this dialog box.

Dim r As Integer

Dim result As Integer

Dim ret As Integer

Page 22: Introduction to 2lwc1/files/files/s3_cl... · 6 Class Work 1.1.3 Decide whether each of the following is True or False. VB expression Result 4 > 2 And 1 = 3 20 < -5 Or 3 >=

22

3.2 InputBox

3.2.1 InputBox syntax

The syntax of InputBox is listed below:

variable = InputBox(Prompt, Title, DefaultResponse)

The InputBox function returns a string, which is the content of the text box inside.

However, if the user presses “Cancel” or the ESC key, an empty string is returned.

The meanings of the parameters are listed below:

Parameter Meaning

Prompt The message inside the InputBox.

Title (Optional) The title of the InputBox. If you don’t specify the title, or

if the title is an empty string, then the title is the name of the

application.

DefaultResponse (Optional) The default response in the text box inside the InputBox.

If you don’t specify the default response, then it is empty.

Note: to input a number, you should pass the return of InputBox into the Val function, i.e.

variable = Val(InputBox(Prompt, Title, DefaultResponse))

3.2.2 InputBox examples

Please refer to the examples below for the usage of InputBox statement.

Dim age As Integer = Val(InputBox("What is your age?"))

Page 23: Introduction to 2lwc1/files/files/s3_cl... · 6 Class Work 1.1.3 Decide whether each of the following is True or False. VB expression Result 4 > 2 And 1 = 3 20 < -5 Or 3 >=

23

Dim name As String = InputBox("Enter your name:",

"Special Program")

Dim guess As Integer = Val(InputBox(

"Please enter a guess between 1 and 100.",

"Guess the Number", "25"))

Class Work 3.2

Write down the InputBox statement that creates the following dialog box, and store the

result in the variable given in the first line of the answer.

Dim answer As Integer

Page 24: Introduction to 2lwc1/files/files/s3_cl... · 6 Class Work 1.1.3 Decide whether each of the following is True or False. VB expression Result 4 > 2 And 1 = 3 20 < -5 Or 3 >=

24

3.3 Miscellaneous example

Example 3.3.1 Using the result of MsgBox

Dim result = MsgBox("Do you want to save the changes to Document1?",

vbExclamation + vbYesNoCancel)

If result = vbYes Then

MsgBox("Saving changes...") ' Replace with real code

ElseIf result = vbNo Then

MsgBox("Discard changes...") ' Replace with real code

Else

MsgBox("Do not close the program.") ' Replace with real code

End If

Example 3.3.2 Miscellaneous example using InputBox and MsgBox

Dim marks As Double = Val(InputBox("Enter your marks in the exam:"))

If marks < 0 Or marks > 100 Then

MsgBox("The marks must be between 0 and 100.", vbCritical)

ElseIf marks >= 50 Then

MsgBox("Pass")

Else

Dim result As Integer = MsgBox("Fail. Will you work harder?",

vbExclamation + vbYesNo)

If result = vbYes Then

MsgBox("Add oil!")

Else

MsgBox("You are lazy!!!")

End If

End If

Page 25: Introduction to 2lwc1/files/files/s3_cl... · 6 Class Work 1.1.3 Decide whether each of the following is True or False. VB expression Result 4 > 2 And 1 = 3 20 < -5 Or 3 >=

25

Chapter 4 String Manipulation

In this chapter, we learn how to operate with strings. A string is a sequence of characters.

Characters are letters, numerical digits, punctuation marks (such as "." or "-"), etc.

4.1 Introduction to string functions

Here is the list of string functions we study in this course.

Function Meaning Example Result

Len

Len(str)

Returns the length of the string,

i.e. its number of characters.

Len("Very good!")

Len("鄧顯")

10

2

Strings.Left

Strings.Left(str, Length)

Returns a specified number of

characters from the left of the

string.

Strings.Left(

"Excellent", 3)

"Exc"

Strings.Right

Strings.Right(str, Length)

Returns a specified number of

characters from the right of the

string.

Strings.Right(

"Excellent", 3)

"ent"

Mid

Mid(str, Start)

Mid(str, Start, Length)

Returns a specified number of

characters from a string. If Length

is not supplied, all characters

from position Start is returned.

Mid("Block", 2, 3)

Mid("clever", 3)

"loc"

"ever"

UCase

UCase(str)

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

LCase

LCase(str)

Convert a string to lower case. LCase("sMaRt") "smart"

Trim

Trim(str)

Remove the spaces at the

beginning and the end of a string.

Trim(" I win! ") "I win!”

InStr

InStr(Start, Str1, Str2)

InStr(Str1, Str2)

Returns an integer which is the

start position of the first

occurrence of Str2 within Str1.

Returns zero if Str2 is not found.

InStr("aabc", "ab")

InStr("abc", "d")

InStr(1,"rear","r")

InStr(2,"rear","r")

2

0

1

4

Page 26: Introduction to 2lwc1/files/files/s3_cl... · 6 Class Work 1.1.3 Decide whether each of the following is True or False. VB expression Result 4 > 2 And 1 = 3 20 < -5 Or 3 >=

26

“Strings” ends with letter “s”. Forgetting the letter “s” will result in an error.

4.2 String functions and their special cases

4.2.1 Len function

Len function returns the number of characters in the string. All characters, including

spaces, punctuation and Chinese characters are counted.

Example 4.2.1 Usage of Len function

Dim TestString As String = "Hello World"

Dim TestLen As Integer = Len(TestString) ' Returns 11.

4.2.2 Strings.Left, Strings.Right functions

Strings.Left and Strings.Right* extract the

specified number of characters from the left and

right of the string respectively. Some special cases are described here:

Condition Strings.Left / Strings.Right returns

Length ≥ length of string Returns the whole string.

Length = 0 Returns an empty string (“”).

Length < 0 Runtime error.

(Note: It does not make sense to pass a negative length to string functions. However, if you

pass a variable length to Strings.Left and Strings.Right, you need to check for this case.)

Example 4.2.2 Usage of Strings.Left and Strings.Right functions

Dim TestString As String = "Hello World!"

Dim result As String

result = Strings.Left(TestString, 5) ' Returns "Hello".

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

result = Strings.Left(TestString, 0) ' Returns "".

result = Strings.Right(TestString, 5) ' Returns "orld!".

result = Strings.Right(TestString, 100) ' Returns "Hello World!".

result = Strings.Right(TestString, 0) ' Returns "".

* You must write Strings.Left and Strings.Right because Left and Right refer to the properties Me.Left and

Me.Right in the form.

Page 27: Introduction to 2lwc1/files/files/s3_cl... · 6 Class Work 1.1.3 Decide whether each of the following is True or False. VB expression Result 4 > 2 And 1 = 3 20 < -5 Or 3 >=

27

4.2.3 Mid function

Mid function extracts the specified number of characters beginning from given starting

position. The position is one-based*, i.e. the left-most character 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 Strings.Left

Start > length of string Returns an empty string (“”).

Start ≤ 0 or Length < 0 Runtime error.

Example 4.2.3 Usage of Mid function

Dim TestString As String = "Mid Function Demo"

Dim FirstWord As String = Mid(TestString, 1, 3) ' Returns "Mid".

Dim LastWord As String = Mid(TestString, 14, 4) ' Returns "Demo".

Dim MidWords As String = Mid(TestString, 5) ' Returns "Function Demo".

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

Example 4.2.4 Usage of UCase and LCase functions

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!".

4.2.5 Trim function

Trim function removes the spaces at the beginning and the end of a string. This is useful to

remove extra spaces accidentally entered by a user.

Example 4.2.5 Usage of UCase and LCase functions

Dim TestString As String = " Hello World! "

Dim result As String = Trim(TestString) ' Returns "Hello World!".

* In computer science, most calculations are zero-based, i.e. starting from zero.

Page 28: Introduction to 2lwc1/files/files/s3_cl... · 6 Class Work 1.1.3 Decide whether each of the following is True or False. VB expression Result 4 > 2 And 1 = 3 20 < -5 Or 3 >=

28

Class Work 4.2

Evaluate the following expressions.

VB expression Result

Strings.Right("polar", 2) &

Strings.Left("ease", 3)

Len("--Computer Literacy--")

"S." & Strings.Left("2A", 1)

Mid("dictionary", 5, 3)

UCase(LCase("Hello!"))

LCase(Trim(" Mr. Wood "))

Dim s As String = "Testing"

s = Mid(s, Len(s) - 2, 2)

4.3 String comparison

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

First, the first characters of the two strings are compared. If the character is different, then

the comparison is finished. Otherwise, the second character is compared, so on. If all the

characters of both strings are equal, then the strings are considered equal. However, if the

characters of only one of the strings are used up in the comparison (and of course all the

characters compared are equal), then the longer string is greater.

Comparison result Reason

"banana" < "cat" The first character is different. (“b” is less than “c”.)

"formal" < "forward" The fourth character is different. (“m” is less than “w”.)

"other" < "otherwise" All characters from “other” are used up.

"car" = "car" All characters are the same.

Page 29: Introduction to 2lwc1/files/files/s3_cl... · 6 Class Work 1.1.3 Decide whether each of the following is True or False. VB expression Result 4 > 2 And 1 = 3 20 < -5 Or 3 >=

29

Besides letters, all other characters, such as digits, symbols, and Chinese characters, can

also be compared. In this course, we discuss only binary comparison of characters, in

which the numeric Unicode code points of the characters are compared. Here are the

Unicode code points (in hexadecimal) of some characters:

Character (sp) ! " # $ % & ' ( ) * + , - . / Unicode code point 0020 0021 0022 0023 0024 0025 0026 0027 0028 0029 002A 002B 002C 002D 002E 002F

Character 0 1 2 3 4 5 6 7 8 9 : ; < = > ? Unicode code point 0030 0031 0032 0033 0034 0035 0036 0037 0038 0039 003A 003B 003C 003D 003E 003F

Character @ A B C D E F G H I J K L M N O Unicode code point 0040 0041 0042 0043 0044 0045 0046 0047 0048 0049 004A 004B 004C 004D 004E 004F

Character P Q R S T U V W X Y Z [ \ ] ^ _ Unicode code point 0050 0051 0052 0053 0054 0055 0056 0057 0058 0059 005A 005B 005C 005D 005E 005F

Character ` a b c d e f g h i j k l m n o Unicode code point 0060 0061 0062 0063 0064 0065 0066 0067 0068 0069 006A 006B 006C 006D 006E 006F

Character p q r s t u v w x y z { | } ~ Unicode code point 0070 0071 0072 0073 0074 0075 0076 0077 0078 0079 007A 007B 007C 007D 007E

You should remember a few points below:

1. Capital letters are always less than small letters.

2. Digits are always less than letters.

3. Space is less than all other characters.

4. You are only required to remember the order of space, 0-9, A-Z, and a-z. Punctuations

marks and symbols are not required.

5. Chinese characters has a Unicode code point of 3000 (hexadecimal) or more. For

example, “鄧” has a Unicode code point of 9127. However, the Unicode code points

of Chinese characters are not ordered in a specific order.

Class Work 4.3

Decide whether each of the following is True or False.

VB 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"

"26726820" < "Tang Hin" And UCase("30th") < "30th"

Page 30: Introduction to 2lwc1/files/files/s3_cl... · 6 Class Work 1.1.3 Decide whether each of the following is True or False. VB expression Result 4 > 2 And 1 = 3 20 < -5 Or 3 >=

30

4.4 Using InStr function to extract contents from a string

If you want 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 (Optional) The starting position of the search. If omitted, then

Start is 1. The position is one-based.

String1 The string to be searched (haystack).

String2 The string to be sought (needle).

If a match is found, InStr returns the position (one-based) where the match begins.

Otherwise, it returns zero. Here are the details:

Condition InStr returns

String2 is found within String1 Position where match begins (one-based)

String2 is not found 0

String1 is empty 0

Start > length of String1 0

String2 is empty, but String1 is not empty Start

Start < 1 Runtime error

To see how the InStr function works, it is best to refer to examples:

Example 4.4.1 Usage of InStr function to extract surname and given names*

Dim name, surname, givenname As String, pos As Integer

name = "Lau Chi Yuen"

pos = InStr(name, " ")

surname = Strings.Left(name, pos - 1) ' Returns "Lau".

givenname = Mid(name, pos + 1) ' Returns "Chi Yuen".

* This example does not work with a real English name, such as Stavroula Andreadakis. Why?

Page 31: Introduction to 2lwc1/files/files/s3_cl... · 6 Class Work 1.1.3 Decide whether each of the following is True or False. VB expression Result 4 > 2 And 1 = 3 20 < -5 Or 3 >=

31

The parameter Start is useful if you need to break a string into 3 or more parts:

Example 4.4.2 Usage of InStr function to extract surname and given names

Dim name, surname, n1, n2 As String

Dim pos1, pos2 As Integer

name = InputBox("Enter your name:")

pos1 = InStr(name, " ")

If pos1 = 0 Then

MsgBox("This is not a name.", vbCritical)

Exit Sub

End If

pos2 = InStr(pos1 + 1, name, " ")

surname = Strings.Left(name, pos1 - 1)

If pos2 > 0 Then

n1 = Mid(name, pos1 + 1, pos2 - pos1 - 1)

n2 = Mid(name, pos2 + 1)

Else

n1 = Mid(name, pos1 + 1)

n2 = ""

End If

MsgBox("Surname: " & surname & vbCrLf &

"n1: " & n1 & vbCrLf & "n2: " & n2)

Class Work 4.4

Evaluate the following expressions.

VB expression Result

Instr("aeroplane", "a")

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

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

Instr("ab", "able")

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

Mid("Zepellin", InStr("Zepellin", "l"))

Page 32: Introduction to 2lwc1/files/files/s3_cl... · 6 Class Work 1.1.3 Decide whether each of the following is True or False. VB expression Result 4 > 2 And 1 = 3 20 < -5 Or 3 >=

32

Exercise 4

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.

2. Write a program that reads a date in the format d/m/y (e.g. 21/2/2013, 5/11/2013).

Your program should find out the day, month and year of the date, and output a

sentence like “Day: 21, Month: 2, Year: 2013”.

Alphabetical Index

A And (operator) ............................ 4

C character ................................... 25

E End (statement) .......................... 8

Exit Sub (statement) ................... 8

I If...Then...Else statement ............ 4

InStr (function) .................... 25, 30

L LCase (function) .................. 25, 27

Len (function) ...................... 25, 26

logical operators ......................... 4

M Mid (function) ..................... 25, 27

MsgBox (function)..................... 15

MsgBox constants

Button sets

vbAbortRetryIgnore ....... 20

vbOkCancel..................... 20

vbOkOnly ........................ 20

vbRetryCancel ................ 20

vbYesNo.......................... 20

vbYesNoCancel ............... 20

Icons

vbCritical ........................ 18

vbExclamation ................ 18

vbInformation ................ 18

vbQuestion ..................... 18

Return values

vbAbort .......................... 20

vbCancel ......................... 20

vbIgnore ......................... 20

vbNo ............................... 20

vbOk ............................... 20

vbRetry ........................... 20

vbYes .............................. 20

N Nested If...Then...Else statement 7

Not (operator)............................. 4

O operator precedence .................. 5

Or (Operator) .............................. 4

R Randomize (function) ............... 10

Rnd (function) ........................... 10

S string ......................................... 25

string comparison ................ 28

string functions .................... 25

Strings.Left (function) ......... 25, 26

Strings.Right (function) ....... 25, 26

T Trim (function) .................... 25, 27

truth table ................................... 5

U UCase (function) ................. 25, 27

Unicode code point ................... 29

V vbCrLf (constant) ...................... 16