59
1 Chapter 2 – Variables, Input, and Output 2.1 Numbers 2.2 Strings 2.3 Input and Output

1 Chapter 2 – Variables, Input, and Output 2.1 Numbers 2.2 Strings 2.3 Input and Output

Embed Size (px)

Citation preview

Page 1: 1 Chapter 2 – Variables, Input, and Output 2.1 Numbers 2.2 Strings 2.3 Input and Output

1

Chapter 2 – Variables, Input, and Output

2.1 Numbers

2.2 Strings

2.3 Input and Output

Page 2: 1 Chapter 2 – Variables, Input, and Output 2.1 Numbers 2.2 Strings 2.3 Input and Output

2

2.1 Numbers• Arithmetic Operations ( 算术运算 ) • Variables ( 变量 )• Incrementing the Value of a Variable ( 累

加 ) • Built-In Functions:

• Math.Sqrt• Int• Math.Round

Page 3: 1 Chapter 2 – Variables, Input, and Output 2.1 Numbers 2.2 Strings 2.3 Input and Output

3

Numbers (continued)• Multiple Declarations ( 多变量的声明 )• Two Integer-Valued Operators ( 整数运

算 )• Parentheses ( 括号对运算顺序的影响 )• Three Types of Errors• The Error List Window

Page 4: 1 Chapter 2 – Variables, Input, and Output 2.1 Numbers 2.2 Strings 2.3 Input and Output

4

Arithmetic Operations• Usually numbers are named as numeric literals ( 数值

文字 , 数字常数 ) , such as 5, 100• There are Five arithmetic operations in Visual Basic

+ addition add(plus) sum

- Subtraction minus difference(remainder)

* Multiplication multiply(times) product

/ division divided by quotient

^ exponentiation power

Page 5: 1 Chapter 2 – Variables, Input, and Output 2.1 Numbers 2.2 Strings 2.3 Input and Output

5

Numeric Expressions

2+3=5 two plus three equals five (2 and 3 is 5)

3*(4+5) three times the sum of four and five

5^2 five square

5^3 five cube

5^4 Five to the fourth power (the fourth power of five)

the square root of five

the cube root of five

the fourth root of five

Page 6: 1 Chapter 2 – Variables, Input, and Output 2.1 Numbers 2.2 Strings 2.3 Input and Output

6

Displaying Numbers

Let n be a number or a numeric expression.

The statement lstBox.Items.Add(n)displays the value of n in the list box.

The statement lstBox.Items.Clear()removes all the items of the list box.

The same way TextBox1.Clear() or TextBox1.Text=“” will clear the content of the text box

Page 7: 1 Chapter 2 – Variables, Input, and Output 2.1 Numbers 2.2 Strings 2.3 Input and Output

7

Example 2-1-1Private Sub btnCompute_Click (...) Handles btnCompute.Click lstResults.Items.Add(5) lstResults.Items.Add(2 * 3) lstResults.Items.Add((2 ^ 3) – 1)End Sub

Output 5in list 6box 7

Page 8: 1 Chapter 2 – Variables, Input, and Output 2.1 Numbers 2.2 Strings 2.3 Input and Output

8

Numeric Variable ( 数值变量 )

A numeric variable is a name respecting to a value in memory, it’s value may be changed with code at run time. Such as: speed, distance.

Declaration Statements: ( 声明语句 ) Dim variablename As DataTypedata (default value is 0)

Dim variablename As DataType = initialvalueAssignment Statements: ( 赋值语句 ) variablename = expression

Page 9: 1 Chapter 2 – Variables, Input, and Output 2.1 Numbers 2.2 Strings 2.3 Input and Output

Numeric Types

Short 16bit -32768 ~ 32767

Integer 32bit -2,147483,648 ~ 2,147483,647

Long 64bit -9.22×1018 ~ 9.22×1018

Single 32bit -3.4×1038 ~ 3.4×1038

Double 64bit -1.7977×10308 ~ 1.7977×10308

Decimal 128bit

9

Page 10: 1 Chapter 2 – Variables, Input, and Output 2.1 Numbers 2.2 Strings 2.3 Input and Output

10

Incrementing the value of a variable

• To add 1 to the numeric variable varvar = var + 1

• Or as a shortcutvar += 1

• The same wayvar -= n

var *= n

var /= n

var ^= n

var1 &= var2

Page 11: 1 Chapter 2 – Variables, Input, and Output 2.1 Numbers 2.2 Strings 2.3 Input and Output

11

Built-in Functions

Functions return a value

Math.Sqrt(9) returns 3

Int(9.7) returns 9

Math.Round(2.7) returns 3

Tips:

Math.Round(2.748, 1) returns 2.7

Math.Round(2.748, 2) returns 2.75

Math.Round(2.75, 1) returns 2.8

Math.Round(2.85, 1) returns 2.8奇进偶不进

如果在代码窗口的通用声明区引入了 Math 函数库,那么程序中所有数学函数就都不用添加 Math 限定了!

Page 12: 1 Chapter 2 – Variables, Input, and Output 2.1 Numbers 2.2 Strings 2.3 Input and Output

12

Example 2-1-4Private Sub btnCompute_Click (...) Handles btnCompute.Click Dim a As Double Dim b As Double a = 2 b = 3 lstResults.Items.Clear() lstResults.Items.Add(Math.Sqrt(5 * b + 1)) lstResults.Items.Add(Int(a ^ b + 0.8)) lstResults.Items.Add(Math.Round(a / b, 3))End Sub

Page 13: 1 Chapter 2 – Variables, Input, and Output 2.1 Numbers 2.2 Strings 2.3 Input and Output

13

Multiple Declarations

Several variables can be declared with a single Dim statement

Dim a, b As Double

Two other types of multiple-declaration statements

Dim a As Double, b As Integer

Dim c As Double = 2, b As Integer = 5

错误写法:Dim a, b, c As Integer = 10

a = b = c = 10

Page 14: 1 Chapter 2 – Variables, Input, and Output 2.1 Numbers 2.2 Strings 2.3 Input and Output

Two Integer-Valued Operators• Integer division (denoted by \) is similar to

ordinary long division except that the remainder is discarded.

• The Mod operator returns only the integer remainder.

23 \ 7 = 3 23 Mod 7 = 2

8 \ 2 = 4 8 Mod 2 = 0

2 \ 5 = 0 2 Mod 5 = 214

Page 15: 1 Chapter 2 – Variables, Input, and Output 2.1 Numbers 2.2 Strings 2.3 Input and Output

15

Parentheses• Parentheses are used to change the priority

levels in numeric expressions.• In the absence of parentheses, the operations

are carried out in the following order: ^, * and /, \, Mod, + and -.

5+10 mod 10 \ 9 / 3 +2 ^2 = ? Key:10

Page 16: 1 Chapter 2 – Variables, Input, and Output 2.1 Numbers 2.2 Strings 2.3 Input and Output

16

Three Types of Errors• Syntax error• Runtime error• Logic error

Page 17: 1 Chapter 2 – Variables, Input, and Output 2.1 Numbers 2.2 Strings 2.3 Input and Output

Error List Window

Dim m; n As Double lstResults.Items.Add(5 lstResults.Items.Add(a)

17

Page 18: 1 Chapter 2 – Variables, Input, and Output 2.1 Numbers 2.2 Strings 2.3 Input and Output

18

Comments and Exercises• Comments P43• Exercises P44

Page 19: 1 Chapter 2 – Variables, Input, and Output 2.1 Numbers 2.2 Strings 2.3 Input and Output

19

2.2 Strings• String Variable• Option Explicit and Option Strict • Using Text Boxes for Input and Output• Auto Correction• String Properties and Methods:

Length ToUpper

Trim ToLower

IndexOf Substring

Page 20: 1 Chapter 2 – Variables, Input, and Output 2.1 Numbers 2.2 Strings 2.3 Input and Output

Strings (continued)• Concatenation• The Empty String • Initial Value of a String • Widening and Narrowing• Internal Documentation• Line Continuation• Scope of a Variable

20

Page 21: 1 Chapter 2 – Variables, Input, and Output 2.1 Numbers 2.2 Strings 2.3 Input and Output

21

String Literal ( 字符常数 ) and String variables

A string literal is a sequence of characters surrounded by quotation marks. Such as "hello", "024-23986531", "Mick John"

A string variable is a name to which a string value can be assigned. Such as address, phoneno

Page 22: 1 Chapter 2 – Variables, Input, and Output 2.1 Numbers 2.2 Strings 2.3 Input and Output

String Variable (continued)• Declaration:

Dim firstName As String

22

variable name data type

• Assignment:firstName = "Fred"

You can declare a string variable and assign it a value at the same time.

Dim firstName As String = "Fred"

Page 23: 1 Chapter 2 – Variables, Input, and Output 2.1 Numbers 2.2 Strings 2.3 Input and Output

Variables VS StringsPrivate Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim president As String president = "George Washington" lstOutput.Items.Add("president") lstOutput.Items.Add(president)End Sub

Output: president George Washington

23

Page 24: 1 Chapter 2 – Variables, Input, and Output 2.1 Numbers 2.2 Strings 2.3 Input and Output

Option Strict • Visual Basic allows numeric variables to be

assigned strings and vice versa, a poor programming practice.

• To prevent such assignments, set Option Strict to On in the Options dialog box, or add Option Strict On statement to the general declarations section in the code editor.

24

Page 25: 1 Chapter 2 – Variables, Input, and Output 2.1 Numbers 2.2 Strings 2.3 Input and Output

Option Strict • Visual Basic allows numeric variables to be

assigned strings and vice versa, a poor programming practice.

• To prevent such assignments, set Option Strict to On in the Options dialog box, or add Option Strict On statement to the general declarations section in the code editor.

25

Page 26: 1 Chapter 2 – Variables, Input, and Output 2.1 Numbers 2.2 Strings 2.3 Input and Output

Rename a variable• If you want to rename a variable, you shouldn’t

change the names one by one.• You should select the variable in code window, right

click it and select Rename.

26

Page 27: 1 Chapter 2 – Variables, Input, and Output 2.1 Numbers 2.2 Strings 2.3 Input and Output

Using Text Boxes for Input and Output

• The contents of a text box is always a string.

• Input example: strVar = txtBox.Text

• Output example: txtBox.Text = strVar

27

Page 28: 1 Chapter 2 – Variables, Input, and Output 2.1 Numbers 2.2 Strings 2.3 Input and Output

Data Conversion

Because the contents of a text box is always a string, sometimes you must convert the input or output if Option Strict is set to On.

dblVar = CDbl(txtBox.Text)

txtBox.Text = CStr(numVar)

28

converts a String to a Double

converts a number to a string

Page 29: 1 Chapter 2 – Variables, Input, and Output 2.1 Numbers 2.2 Strings 2.3 Input and Output

29

Auto CorrectionThe Auto Correction feature of IntelliSense

suggests corrections when errors occur and allows you to select a correction to be applied to the code.

Page 30: 1 Chapter 2 – Variables, Input, and Output 2.1 Numbers 2.2 Strings 2.3 Input and Output

Concatenation

Combining two strings to make a new string

quote1 = "We'll always "quote2 = "have Paris."quote = quote1 & quote2txtOutput.Text = quote & " - Humphrey Bogart"

Output:We'll always have Paris. - Humphrey Bogart

30

Page 31: 1 Chapter 2 – Variables, Input, and Output 2.1 Numbers 2.2 Strings 2.3 Input and Output

String Properties and Methods "Visual".Length is 6.

"Visual".ToUpper is VISUAL.

"123 Hike".ToLower is 123 hike.

"a" & " bcd ".Trim & "efg" is abcdefg

"a" & " bcd ".TrimStart & "efg" is abcd efg

"a" & " bcd ".TrimEnd & "efg" is a bcdefg

31

Page 32: 1 Chapter 2 – Variables, Input, and Output 2.1 Numbers 2.2 Strings 2.3 Input and Output

Positions in a String Positions of characters in a string are numbered 0, 1,

2, ….

Consider the string “Visual Basic”.

Position 0: V

Position 1: i

Position 7: B

Substring “al” begins at position 4

32

Page 33: 1 Chapter 2 – Variables, Input, and Output 2.1 Numbers 2.2 Strings 2.3 Input and Output

Substring Method Let str be a string.

str.Substring(m, n) is the substring of length n, beginning at position m in str.

“Visual Basic”.Substring(2, 3) is “sua”

“Visual Basic”.Substring(0, 1) is “V”

33

Page 34: 1 Chapter 2 – Variables, Input, and Output 2.1 Numbers 2.2 Strings 2.3 Input and Output

IndexOf Method Let str1 and str2 be strings.

str1.IndexOf(str2)

is the position of the first occurrence of str2 in str1.

(Note: Has value -1 if str2 is not a substring of str1.)

"Visual Basic".IndexOf("is") is 1.

"Visual Basic".IndexOf("si") is 9.

"Visual Basic".IndexOf("ab") is -1.

34

Page 35: 1 Chapter 2 – Variables, Input, and Output 2.1 Numbers 2.2 Strings 2.3 Input and Output

The Empty String • The string "", which has no characters, is

called the empty string or the zero-length string.

• The statement lstBox.Items.Add("") skips a line in the list box.

• The contents of a text box can be cleared with either the statement

txtBox.Clear()

or the statement txtBox.Text = ""

35

Page 36: 1 Chapter 2 – Variables, Input, and Output 2.1 Numbers 2.2 Strings 2.3 Input and Output

Initial Value of a String Variable

• By default the initial value is the keyword Nothing

• You must assign a value to a string variable even just an empty sting before using it

• Strings can be given a different initial value as follows:

Dim name As String = "Fred"

36

Page 37: 1 Chapter 2 – Variables, Input, and Output 2.1 Numbers 2.2 Strings 2.3 Input and Output

Widening and Narrowing• Widening: assigning an Integer value to

a Double variable. No conversion function needed.

• Narrowing: assigning a Double value to an Integer variable. Narrowing requires the Cint function

37

Page 38: 1 Chapter 2 – Variables, Input, and Output 2.1 Numbers 2.2 Strings 2.3 Input and Output

Internal Documentation(Remarks 注释、 Comment Statements 注释语句 )

You may add comment statement with an apostrophe at the beginning of the statement. Or using Comment Out button on the tool bar.

1. Other people can easily understand the program.

2. You can understand the program when you read it later.

3. Long programs are easier to read because the purposes of individual pieces can be determined at a glance.

38

Page 39: 1 Chapter 2 – Variables, Input, and Output 2.1 Numbers 2.2 Strings 2.3 Input and Output

Line Continuation

A long line of code can be continued on another line by using an underscore (_) preceded by a space

msg = "I'm going to make " & _

"him an offer he can't refuse."

39

Page 40: 1 Chapter 2 – Variables, Input, and Output 2.1 Numbers 2.2 Strings 2.3 Input and Output

Implicit Line Continuation

The line continuation character can be omitted after a comma, ampersand, or arithmetic operator.

msg = "I'm going to make " & "him an offer he can't refuse."

average = sumOfNumbers /

numberOfNumbers

40

Page 41: 1 Chapter 2 – Variables, Input, and Output 2.1 Numbers 2.2 Strings 2.3 Input and Output

Scope ( 作用域 )

• The scope of a variable is the portion of the program that can refer to it.

• Variables declared inside an event procedure are said to have local scope and are only available to the event procedure in which they are declared.

41

Page 42: 1 Chapter 2 – Variables, Input, and Output 2.1 Numbers 2.2 Strings 2.3 Input and Output

Scope (continued)• Variables declared outside an event

procedure are said to have class-level scope and are available to every event procedure.

42

Page 43: 1 Chapter 2 – Variables, Input, and Output 2.1 Numbers 2.2 Strings 2.3 Input and Output

Automatic Colorization

Comments – green

String literals – maroon 栗色Keywords – blue

Class Name – turqoise 青绿色Note: Examples of keywords are Handles,

Sub, and End. Examples of class names are Form1, Math, and MessageBox.

43

Page 44: 1 Chapter 2 – Variables, Input, and Output 2.1 Numbers 2.2 Strings 2.3 Input and Output

44

Comments and Exercises• Comments P56• Exercises P57

Page 45: 1 Chapter 2 – Variables, Input, and Output 2.1 Numbers 2.2 Strings 2.3 Input and Output

2.3 Input and Output• Formatting Output with Format Functions• Using a Masked Text Box for Input• Dates as Input and Output• Getting Input from an Input Dialog Box• Using a Message Dialog Box for Output• Named Constants• Sending Output to the Printer

45

Page 46: 1 Chapter 2 – Variables, Input, and Output 2.1 Numbers 2.2 Strings 2.3 Input and Output

46

Formatting Output with Format Functions

Function String Value

FormatNumber(12345.628, 1) 12,345.6

FormatCurrency(12345.628, 2) $12,345.63

FormatPercent(0.183, 0) 18%

Page 47: 1 Chapter 2 – Variables, Input, and Output 2.1 Numbers 2.2 Strings 2.3 Input and Output

VB2010保留的 VB6格式的格式输出函数

Syntax : Format(expression , format-String )

Char Function Expression Format-String Result0 带几个整数位和小数位 1234.56

1234.56“000000.0000”

“00.0”001234.5600

1234.6

# 带几个整数位和小数位 1234.561234.56

“# # # # #. # # # #”“# #. # ”

1234.561234. 6

. 对于整数也加小数点 123 “00.00” 123.00

, 是否显示千分位 12345.6 “# #,# # 0. 0 0 ” 12,345.60

% 乘 100 再加 % 12.3 “# # 0. 00%” 1230.00%

$ 前面加 $ 100.15 “$# # #. # #” $100.15

Forexample: TextBox1.Text = Format(1234.567, "$#,##0.00")Result: $1,234.57

小数位不能多也不能少整数为只能多,不能少

小数位不可以多,可以少整数位可以多也可以少

Page 48: 1 Chapter 2 – Variables, Input, and Output 2.1 Numbers 2.2 Strings 2.3 Input and Output

48

Masked Text Box Control

It’s similar to an ordinary text box, but has a Mask property that restricts what can be typed into the masked text box.

Tasks button

Click on the Tasks button to reveal the Set Mask property.

Page 49: 1 Chapter 2 – Variables, Input, and Output 2.1 Numbers 2.2 Strings 2.3 Input and Output

49

Input Mask Dialog Box

Page 50: 1 Chapter 2 – Variables, Input, and Output 2.1 Numbers 2.2 Strings 2.3 Input and Output

Mask

A Mask setting is a sequence of characters, with 0, L, and & having special meanings.•0 Placeholder for a digit•L Placeholder for a letter ( 英文字母 )

•& Placeholder for a character ( 任意字符 )

50

Page 51: 1 Chapter 2 – Variables, Input, and Output 2.1 Numbers 2.2 Strings 2.3 Input and Output

Sample Masks • State abbreviation: LL

For example: CA ( 加尼福尼亚 ) HI ( 夏威夷 )

• Phone number: 000-00000000 ( 中国的号码格式 )

For example: 024-23986531 拨打国际电话为 0086-24-23986531

• Social Security Number: 000-00-0000

• License plate( 车牌 ): &&&&&&

51

Page 52: 1 Chapter 2 – Variables, Input, and Output 2.1 Numbers 2.2 Strings 2.3 Input and Output

Dates as Input and Output• : #7/4/1776#

• Declarons:

Dim indDay As Date

Dim d As Date = CDate(txtBox.Text)

Dim indDay As Date = #7/4/1776#

52

Date literals must be surrounded by number signs

提示: 如果在文本框中输入日期,用 CDate 函数转换后为日期型变量赋值,那么输入2014 年 1 月 20 日、 2014-1-20 、 1-20-2014 、 2014/1/20 、 1/20/2014 都行。但是不能以“日 - 月 - 年”的格式输入 ( 例如 20-1-2014) ,除非你把系统设为英国格式! 如果采用日期常数直接为变量赋值。那么只能以 #1-20-2014# 或 #1/20/2014# 的格式输入 ( 系统会自动把 #1-20-2014# 转换为 #1/20/2014#)

Page 53: 1 Chapter 2 – Variables, Input, and Output 2.1 Numbers 2.2 Strings 2.3 Input and Output

Useful Functions and MethodsFunctions:FormatDateTime (datevariable, DateFormat.LongDate)

TextBox1.Text=FormatDateTime (Today, DateFormat.LongDate)

Result: Saturday, March 01, 2014 ( 系统设置为美国格式 )

2014 年 3 月 1 日 ( 系统设置为中国格式 ) DateFormat.ShortDate 3/1/2014( 美国格式 ) 2014/3/1( 中国格式 ) DateFormat.LongTime 8:25:30

DateFormat.ShortTime 8:25

53

Functions for getting date and time: txtBox.Text = Today 2014/3/12

txtBox.Text = TimeOfDay 8:32:46txtBox.Text = Now 2014/3/12 8:32:46

Page 54: 1 Chapter 2 – Variables, Input, and Output 2.1 Numbers 2.2 Strings 2.3 Input and Output

Useful Functions and Methods

54

Functions:DateDiff (interval, Date1, Date2)

TextBox1.Text=DateDiff(DateInterval.Day, #3/1/2014#, #4/1/2014#)

Result: 31 DateDiff(DateInterval.Day, #4/1/2014#, #3/1/2014#) 结果为 -31

DateAdd (interval, number, Date1)

TextBox1.Text=DateAdd(DateInterval.Day, 5, #3/20/2014#)

Result: 3/25/2014 DateAdd(DateInterval.Day,-5,#3/20/2014#) 结果为 3/15/2014

Other intervals are: DateInterval.Year, DateInterval.Month, DateInterval.Hour, DateInterval.Minute, DateInterval.Second

Page 55: 1 Chapter 2 – Variables, Input, and Output 2.1 Numbers 2.2 Strings 2.3 Input and Output

Useful Functions and Methods

55

Methods for Date : AddYears(n) 、 AddMonths(n) 、 AddDays(n) 、 AddHours(n) 、 AddMinutes(n) 、 AddSeconds(n)

Dim D1 As Date = #1/20/2014#

TextBox1.Text = D1.AddDays(10)Result : 1/30/2014

提示: 如果采用 AddMonths 方法,那么 #1-20-2014# 加一个月的结果是 #2-20-2014# ,但是如果结果超出了本月的范围,例如 #1-31-2014# 加一个月或三个月没有2 月 31 日和 4 月 31 日,则取结果月中的最后一天,即: #2-28-2014# 和 #4-30-2014#

Page 56: 1 Chapter 2 – Variables, Input, and Output 2.1 Numbers 2.2 Strings 2.3 Input and Output

56

Getting Input from an Input Dialog Box

stringVar = InputBox(prompt, title, default value)

fullName = InputBox("Enter your full name.", “Get Name" , "Jack Chen" )

title

prompt

Page 57: 1 Chapter 2 – Variables, Input, and Output 2.1 Numbers 2.2 Strings 2.3 Input and Output

57

Using a Message Dialog Box for Output

MessageBox.Show(prompt, title)

MessageBox.Show("Nice try, but no cigar.", "Consolation")

title

prompt

Example

详细用法

Page 58: 1 Chapter 2 – Variables, Input, and Output 2.1 Numbers 2.2 Strings 2.3 Input and Output

Named Constants• Declared with Const CONSTANT_NAME As DataType = value

• Value cannot be changed.

Examples: Const MIN_VOTING_AGE As Integer = 18

Const INTEREST_RATE As Double = 0.035

Const TITLE As String = "Visual Basic"

58

Page 59: 1 Chapter 2 – Variables, Input, and Output 2.1 Numbers 2.2 Strings 2.3 Input and Output

64

Comments and Exercises• Exercises P68