javafor循環怎麼寫
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); }}。