開心生活站

位置:首頁 > 綜合知識 > 

javafor循環怎麼寫

1. Java for循環幾種寫法整理

1:遍歷數組的傳統方式/* 建立一個數組 */ int[] integers = {1, 2, 3, 4};/* 開始遍歷 */ for (int j = 0; j strings = new ArrayList< String>(); strings.add("A"); strings.add("B"); strings.add("C"); strings.add("D"); for (String str : integers) { System.out.println(str);/* 依次輸出“A”、“B”、“C”、“D” */ } 11:使用要被遍歷的對象中的元素的上級類型的循環變量 String[] strings = {"A", "B", "C", "D"}; Collection< String> list = java.util.Arrays.asList(strings); for (Object str : list) { System.out.println(str);/* 依次輸出“A”、“B”、“C”、“D” */ } 12:使用能和要被遍歷的對象中的元素的類型自動轉換的類型的循環變量 int[] integers = {1, 2, 3, 4}; for (Integer i : integers) { System.out.println(i);/* 依次輸出“1”、“2”、“3”、“4” */ }。

javafor循環怎麼寫
2. JAVA中for循環的這種寫法怎麼理解

這是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); }}。

標籤:javafor