一个关于java array的问题

翻到好久之前一个问题,然后咋做都不会了
part1

public static int[] getIndices(String[] sa, String s) {

    int[] result = null;
    int f = 0 ;
    int count =0;
    for (int i= 0;i < sa.length;i ++ ) {
           
        if (sa[i].equals(s)) {
       f=i;
         count ++;
              
   

                    }
       
                       result = new int [count];
       for(int j =0;j<count;j++) {    
                          
           result[j]=f;
           
       }

        }
 
 
        
        
    
    

    return result;
}

}

part2:@Test
public void test_getIndices_01() {
String[] input = {"d", "c", "a", "b", "c", "d", "a", "a", "d", "a"};
int[] result = Utilities.getIndices(input, "a");
int[] expected = {2, 6, 7, 9};
assertArrayEquals(expected, result);
}
@Test
public void test_getIndices_02() {
String[] input = {"d", "c", "a", "b", "c", "d", "a", "a", "d", "a"};
int[] result = Utilities.getIndices(input, "b");
int[] expected = {3};
assertArrayEquals(expected, result);
}

@Test
public void test_getIndices_03() {
    String[] input = {"d", "c", "a", "b", "c", "d", "a", "a", "d", "a"};
    int[] result = Utilities.getIndices(input, "e");
    int[] expected = {};
    assertArrayEquals(expected, result);
}

}

给出一个String []然后里面有几个字母;再输入一个string,若输入的string和String[]里的元素相同则输出result[] result的元素就是string在 String[] 所在的位置;
以上代码的part1 是我写的 part2 是junittest, 运行之后result里的元素只有string在String[] 最后出现的位置。
望大家可以找出问题并解答
不胜感激

因为你f变量只能保存一个值,前面循环结束后 f 中就只是最后一次赋值的值。
需要把f也改成数组才能保存每一个值
并且 result = new int [count];创建数组不要在循环中重复创建,要在循环外创建。
之后把f数组中元素复制到result数组中即可。

你题目的解答代码如下:

public static int[] getIndices(String[] sa, String s) {
 
    int[] result = null;
    int[] f = new int[sa.length];
    int count = 0;
    for (int i= 0;i < sa.length;i++ ) {
        if (sa[i].equals(s)) {
           f[count] = i;
            count ++;
        }
    }
    result = new int [count];
    for(int j =0;j<count;j++) {    
        result[j]=f[j];
    }
    return result;
}

如有帮助,请点击我的回答下方的【采纳该答案】按钮帮忙采纳下,谢谢!

img