具體介紹四大類VB.NET循環(huán)
VB.NET有很多值得學(xué)習(xí)的地方,這里我們主要介紹VB.NET循環(huán),VB.NET循環(huán)有三種形式:For/Next循環(huán)、While/End While循環(huán)、Do/Loop循環(huán)和For/Each循環(huán)。
1. For/Next循環(huán)
用For/Next循環(huán)可以精確地控制循環(huán)體的執(zhí)行次數(shù)。For/Next循環(huán)的語法如下:
- For counter = startvalue To endvalue [Step stepvalue]
- [statements]
- [Exit For]
- [statements]
- Next
其中,用Step關(guān)鍵字可以定義循環(huán)計(jì)數(shù)器的增長方式,stepvalue的值(可正可負(fù))來適應(yīng)各種不同的需求。Exit For語句允許在某種條件下直接退出循環(huán)體。用For/Next語句來實(shí)現(xiàn)顯示二維數(shù)組的內(nèi)容。
- <%
- Dim arrData(1,2)
- Dim intI,intJ as Integer
- arrData(0,0)=12
- arrData(0,1) =13
- arrData(0,2) =14
- arrData(1,0) =15
- arrData(1,1) =16
- arrData(1,2) =17
- For intI=0 To 1
- For intJ=0 To 2
- Response.Write (arrData(intI,intJ) & " ")
- Next
- Response.Write ("<br>")
- '一行顯示完以后換行顯示下一行
- Next
- %>
可以看出,用For/Next循環(huán)來顯示數(shù)組這樣的可以確定循環(huán)次數(shù)的數(shù)據(jù)結(jié)構(gòu)是十分方便的。
2. While/End While 循環(huán)
如果不清楚要執(zhí)行的循環(huán)的次數(shù),那么可以用While/ End While循環(huán)。它有一個(gè)檢測條件,當(dāng)條件滿足時(shí),執(zhí)行循環(huán)體的內(nèi)容。如果條件不滿足,就退出循環(huán)。While/ End While語法如下:
- While condition
- [statements]
- End While
由于在進(jìn)入循環(huán)體之前會(huì)遇到檢測條件,所以如果這個(gè)時(shí)候condition的值為False,那么While/ End While循環(huán)的循環(huán)體有可能一次也不能執(zhí)行。顯示3次問候信息。
- <%
- Dim intI as Integer
- IntI=0
- While intI<3
- Response.Write ("Hello! Cindy!" & "<br>")
- IntI=intI+1
- End While
- %>
在這個(gè)例子的第3行中為第2行中定義的intI變量設(shè)置了初值0。這里,如果不設(shè)置初值也是可以的,系統(tǒng)會(huì)自動(dòng)為intI進(jìn)行初始化(VB.NET默認(rèn)為未顯式初始化的整數(shù)初始化為0)。但是,建議養(yǎng)成為變量設(shè)置初值的好習(xí)慣,這樣可以防止很多意想不到的錯(cuò)誤。
3. Do/Loop
同樣,在不知道循環(huán)次數(shù)的情況下,也可以使用Do/Loop 循環(huán)。Do/Loop循環(huán)的作用與While/ End While十分相似。它的語法是:
- Do {While | Until} condition
- [statements]
- [Exit Do]
- statements]
- Loop
其中,Do后面的While和Until是可選的。使用While時(shí),后面的條件滿足則執(zhí)行循環(huán)體;使用Until時(shí),后面的條件滿足就退出循環(huán)體。Do/Loop循環(huán)還有另外一種寫法:
- Do
- [statements]
- [Exit Do]
- [statements]
- Loop {While | Until} condition
這種寫法的結(jié)果是:循環(huán)體在執(zhí)行的時(shí)候至少會(huì)執(zhí)行一次。顯示3次問候信息。
- <%
- Dim intI
- IntI=0
- Do Until intI>2
- Response.Write ("Hello! Cindy!" & "<br>")
- IntI=intI+1
- Loop
- %>
可以看出,Do/Loop的執(zhí)行和While/End While的執(zhí)行沒有太大的區(qū)別。用戶也可以把上面例子中第4行中的Until改為While并相應(yīng)地改變后面的條件來實(shí)現(xiàn)相同的功能。
4. For/Each
在某些特殊情況下,可以使用For/Each來實(shí)現(xiàn)對一個(gè)數(shù)組或集合(集合將在后面的章節(jié)中講解)中元素的遍歷。
For/Each語句的寫法如下:
- For Each item In Array or Collection
- [statements]
- Next
用For/Each顯示一個(gè)數(shù)組中的所有數(shù)據(jù)。
- <%
- Dim arrData(3)
- Dim stritem as string
- arrData(0)="Beijing"
- arrData(1)="Shanghai"
- arrData(2)="Guangzhou"
- For Each stritem In arrData
- Response.Write (stritem & "<br>")
- Next
- %>
可以看出,F(xiàn)or/Each循環(huán)與For/Next循環(huán)的區(qū)別是:在For/Next循環(huán)中需要指明循環(huán)的次數(shù),而在For/Each循環(huán)中不需要這樣就可以遍歷到一個(gè)數(shù)組或集合的所有內(nèi)容。另外需要說明的是,這種循環(huán)通常在集合中使用。以上介紹VB.NET循環(huán)。
【編輯推薦】