2016-01-13 167 views
-1

enter image description here增強的for循環錯誤

public class ArrayMethodsTest 
{ 
    public static void main(String[] args) 
    { 

     int[] tester = {0,1,2,3,4,5}; 
     ArrayMethods test = new ArrayMethods(tester); 
     for(int element : test) 
     { 
      System.out.print(element + " "); 
     } 
     test.shiftRight(); 
     for(int element : test) //error: for-each not applicable to expression type 
     { 
      System.out.print(element + " "); 
     } 
    } 
} 

我想,是什麼問題。感謝jigar joshi。不過,我仍然需要爲我創建的測試程序使用ArrayMethods方法。我知道它們的工作原理,但是如何爲一個非數組的對象提供一個測試器類,因爲這些方法是用於數組的。

public class ArrayMethods 
{ 
    public int[] values; 
    public ArrayMethods(int[] initialValues) 
    { 
     values = initialValues; 
    } 
    public void swapFirstAndLast() 
    { 
     int first = values[0]; 
     values[0] = values[values.length-1]; 
     values[values.length-1] = first; 

    } 
    public void shiftRight() 
    { 
     int first = 0; 
     int second = first; 
     for(int i =0; i < values.length; i++) 
     { 
     if(i < values.length-1) 
     { 
      first = values[i]; 
      second = values[i+1]; 
      values[i+ 1] = first; 
     } 
     if(i == values.length) 
     { 
      values[i] = values[0]; 
     } 
     } 
    } 

} 
//0,1,2,3,4,5 
//5,0,1,2,3,4 
+1

您在for-each循環中清楚地引用了非'Iterable'。 – Mena

+0

ArrayMethods的代碼是什麼?第一個'for(int element:test)'的代碼是否也出錯? –

+0

因爲ArrayMethods類中的數組是公開的,所以可以使用for(int element:test.values)' –

回答

1

testArrayMethods參考這是不是一個Iterable或數組類型,所以是你已經遇到了,你不能遍歷一個ArrayMethods問題上的錯誤

0

,因爲它是不可迭代。看起來你想是迭代其值,考慮到values是一個公共領域。

for(int element : test.values) { 
    System.out.print(element + " "); 
}