javafor迴圈怎麼寫
- 綜合知識
- 關注:2.26W次
1:遍歷陣列的傳統方式/* 建立一個數組 */ int[] integers = {1, 2, 3, 4};/* 開始遍歷 */ for (int j = 0; j
這是JAVA1.5 增強的for 迴圈的新特性。。(enhanced for loop)
所謂“增強的for 迴圈”,主要也是針對容器的。使用該項特性時,開發者可以將“利用iterator
遍歷容器”的邏輯交給編譯器來處理。例如下列程式碼:
void cancelAll(Collection c) {
for (Iterator i = c.iterator(); i.hasNext(); ) {
TimerTask tt = (TimerTask) i.next();
tt.cancel();
}
}
可以用增強的for 迴圈改寫為:
void cancelAll(Collection c) {
for (Object o : c)
((TimerTask)o).close();
}
編譯器判斷物件c 是一個Collection 子物件(即是容器)之後,就會允許使用增強的for 迴圈
形式,並自動取到c 的迭代器,自動遍歷c 中的每個元素。
可以看到,上面的程式碼中仍然有一個強制型別轉換(((TimerTask)o).close();)。實際上,這
項特性應該普遍地與泛型結合,以獲得最大的利益。結合泛型之後,上述程式碼變成:
void cancelAll(Collection c) {
for (TimerTask task : c)
task.cancel();
}
3. java中for迴圈這樣寫是什麼意思遍歷List的另一種寫法
相當於
List<WebElement> element = driver.findElements(By.tagName("input"));
for (int 1=0;i<element.size();i++){
WebElement e = element.get(i);
System.out.println(e.getAttribute("id"));
}
4. java for 迴圈語句這個可能對於初學者不好理解,可是我幫你改成對應的while迴圈,你應該會更容易理解一些,你可以看一下。
public class control6{ public static void main(String[] args){ int x; int n=100; x=1; while(n>0){ //要一直當n減到0才跳出迴圈 n--; x++; } System.out.println(x); }}或者你把你程式的for寫簡單點,比如:public class control6{ public static void main(String[] args){ int x; int n=100; for(x=1;n>0;n--){ x++; } System.out.println(x); }}。
- 文章版權屬於文章作者所有,轉載請註明 https://shqsg.com/zonghezhishi/zk32v6.html