我试图从数组中提取特定的索引值,并将它们放入一个新数组中。主要数组值如下:
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} {}
提前致谢......
最佳答案
小建议:
for (index = 0; index < count; index++)
{
result[index] = spotIndex;
index++;
}
你索引++调用了两次。在方法范围内使用索引是不好的做法,更好的是:
for (int index = 0; index < count; index++)
{
result[index] = spotIndex;
}
请注意,您在所有结果元素中放置了 spotIndex(相同的值)。
为什么不使用列表?
public Integer[] findAll(int a[], int target) {
List<Integer> result = new ArrayList<Integer>();
for (int i=0; i<a.length; i++) {
if (a[i] == target) {
result.add(i);
}
}
return result.toArray(new Integer[result.size()]);
}
关于java - 嵌套循环将索引值提取到新数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5286909/