-1
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
您在for-each循環中清楚地引用了非'Iterable'。 – Mena
ArrayMethods的代碼是什麼?第一個'for(int element:test)'的代碼是否也出錯? –
因爲ArrayMethods類中的數組是公開的,所以可以使用for(int element:test.values)' –