2017-09-05 20 views
0

環,我可以從string [] array像這樣的例子進行個別strings的Android與String []數組

//first, make stringArray1 the same size as arrayList1 
stringArray1 = new String[arrayList1.size()]; 

//stringArray1 will contain all the values in arrayList1 
stringArray1 = arraylist1.toArray(stringArray1); 

//for each value in stringArray1 make it into an individual string, 
//called string1 
      for(String string1: stringArray1) 

      { 
       System.out.println("string1 is " + string1); 

      } 

你能告訴我怎麼會把另一個字符串轉換,從string [] array到同一for循環? arrayList1arrayList2的尺寸完全相同。我以爲我能夠使用&&但沒有喜悅。我得到'Expression expected'。或者我需要有兩個不同的for循環? 這是我有:

//first, make stringArray1 the same size as arrayList1 
stringArray1 = new String[arrayList1.size()]; 

//second, make stringArray2 the same size as arrayList2 
stringArray2 = new String[arrayList2.size()]; 

//stringArray1 will contain all the values in arrayList1 
stringArray1 = arraylist1.toArray(stringArray1); 

//stringArray2 will contain all the values in arrayList2 
stringArray2 = arraylist2.toArray(stringArray2); 

//for each value in stringArray1 make it into an individual string, 
//called string1. Do likewise for string2 
      for(String string1: stringArray1 && String string2: stringArray2) 

      { 
       System.out.println("string1 is " + string1); 
       System.out.println("string2 is " + string2); 

      } 
+0

這是行不通的。每個循環有兩個或將數組收集到一箇中。 –

+0

另外從兩個陣列可以有不同的大小。然後每個循環都無法處理。 –

+0

@ MuratK.Thanks評論,兩個陣列將是完全相同的大小。 – CHarris

回答

2

你不能使用增強型for-loop(foreach循環)同時迭代兩個數組。這是因爲這種foreach循環在內部使用Iterator實例遍歷元素。

您有幾種選擇:

  • 使用一個簡單的for循環:

    for (int i = 0; i < arr1.length; i++) { 
        System.out.println(arr1[i]); 
        System.out.println(arr2[i]); 
    } 
    

    當然,你得保證數組的大小相同,否則ArrayIndexOutOfBoundsException被髮射。

    要靜默停止,如果陣列中的一個被耗盡,您可以使用此:

    Iterator<T> it1 = arr1.iterator(); 
    Iterator<U> it2 = arr2.iterator(); 
    while (it1.hasNext() && it2.hasNext()) { 
        // Do something with it1.next() 
        // Do something with it2.next() 
    } 
    
  • 您也可以更改代碼生成兩個ArrayList S,並確保它返回一個清單,包含來自第一陣列的元素和來自第二陣列的對應元素的封裝對象。

3

如果他們有,你可以做這樣的事情同樣大小:

for (i=0; i<arrayList1.size();i++){ 
    System.out.println("string1 is " + arrayList1[i]); 
    System.out.println("strin2 is " + arrayList2[i]); 
} 

但使用arrayList1.size()是不是最好的方式,我認爲

+0

只是爲了安全起見,你應該檢查是否是'arrayList1.size()'或'arrayList2.size()'是大於另一個避免異常 –

+0

大,會嘗試在家裏。如果出現異常情況,那麼試試抓住最好呢? – CHarris

+1

要麼這或你只是檢查'如果(arrayList1.size()== arrayList1.size()){...} –