Dùng DO WHILE Loop statement

Một phần của tài liệu giáo trình giáo trình visual basic 6 full toàn tập (Trang 36 - 37)

Khi ta không biết chắc là execution sẽđi qua loop bao nhiêu lần thì tốt nhất là dùng DO WHILE Loop statement. Khàc với FOR Loop, trong DO WHILE Loop ta phải tự lo initialisation (tức là mới vô đầu i bằng bao nhiêu) và tự lo tăng value của parameter i. Nếu Logical Expression là True thì execute những dòng code từDO WHILE cho đến Loop.

Thí dụ mới vừa qua có thể viết lại bằng cách dùng DO WHILE Loop như sau: Private Sub cmdWorkOut_Click()

Dim i, Total

CInt

Total = 0 ' Initialise Total value to zero i = 1 ' Intialise at the first character

Do While (Total < WantedTotal) ' Logical Expression is (Total < WantedTotal) Total = Total + i ' Add the number to the Total

i = i + 1 ' Increment the vakue of i Loop Loop

txtActualtotal.Text = CStr(Total) ' Display the Actual Total txtUptonumber.Text = CStr(i - 1) ' Display the highest number End Sub

TRong khi Total hãy còn nhỏ hơn WantedTotal thì ta tiếp tục đi qua While Loop. Giả dụ ta có các hàng text chứa giá tiền các thứ có thể bỏ vào ổ bánh mì thịt với giá như sau:

Chicken Roll 45c Roast Beef 55c Tomato Sauce 5c

Bây giờ ta muốn viết code để lấy ra giá tiền từ những hàng Text string như trên. Ta sẽđi từ bên phải lần lần qua trái cho đến khi tìm được một blank space.

Private Sub WorkOutPrice_Click() Dim i, TStr, PriceInCents, Price TStr = "Chicken Roll 45c"

i = Len(TStr) ' Starting from the rightmost character of the text string ' Going from right to left, look for the first blank character

Do While (Mid(TStr, i, 1) <> " ") i = i - 1 ' Keep walking to the left Loop

PriceInCents = Mid(TStr, i + 1) ' String including character "c"

' Discard the rightmost character which is "c" and convert the price string to single number Price = CSng(Left(PriceInCents, Len(PriceInCents) - 1))

txtPrice.Text = CStr(Price) ' Display the highest number End Sub

Một phần của tài liệu giáo trình giáo trình visual basic 6 full toàn tập (Trang 36 - 37)