我想從數組中提取特定索引值,並將它們放入新數組中。主陣列的值如下:嵌套循環提取索引值到新陣列中
int a[] = {7, 8, 9, 9, 8, 7};
我提出的方法的調用如下:
print(findAll (a,7));
print(findAll (a,2));
我使用的方法如下:
public int[] findAll(int a[], int target)
{
int count = 0;
int i = 0;
int index = 0;
int spotIndex = 0;
for (i = 0; i < a.length; i++)
{
if (a[i] == target)
count = count + 1;
spotIndex = i;
}
int result[] = new int[count];
for (index = 0; index < count; index++)
{
result[index] = spotIndex;
index++;
}
return result;
}
結果應該是:
{0,5} {}
我的結果如下;如果我改變目標參數,我會得到相同的結果。
{5,0} {}
在此先感謝....
太棒了,非常感謝解釋!湯姆 – user592646 2011-03-13 03:37:31