當前位置:生活全書館 >

綜合知識

> javafor迴圈怎麼寫

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
  • 文章版權屬於文章作者所有,轉載請註明 https://shqsg.com/zonghezhishi/zk32v6.html